简体   繁体   中英

How to convert American date format to European

from : 5/19/2011

to : 2011-05-19

I need it to raise an error when it finds that it cannot be real like 5/40/2011 etc. Are there any libraries that do it well?

maybe this is not best solution, but you can try the simple way like:

var from="5/19/2011";
var temp = from.split("/");
var to = temp[2] + "-" + temp[0] + "-" + temp[1];

How about Datejs an open source date library? Specifically:

http://code.google.com/p/datejs/wiki/APIDocumentation#parseExact

Date.parseExact("10/15/2004", "M/d/yyyy");  // The Date of 15-Oct-2004
Date.parse("15-Oct-2004", "d-MMM-yyyy");    // The Date of 15-Oct-2004
Date.parse("2004.10.15", "yyyy.MM.dd");     // The Date of 15-Oct-2004
Date.parseExact("10/15/2004", ["M/d/yyyy", "MMMM d, yyyy"]); // The Date of 15-Oct-2004

Return Value {Date} A Date object or null if the string cannot be converted into a Date.

or

http://code.google.com/p/datejs/wiki/APIDocumentation#validateDay

Date.validateDay(15, 2007, 1);  // true, 15-Feb-2007
Date.validateDay(31, 2007, 10); // false, throws RangeError exception

Return Value {Boolean} true if within range, otherwise false.

Keep it simple:

[ edit ] right, you wanted a check too, so added fn chkDat :

function zeroPad(n){
  return (parseInt(n,10)<10 ? '0' : '') + n;
}

var usdat = '5/19/2011'.split('/')
    ,eudat = [usdat[2],zeroPad(usdat[0]),zeroPad(usdat[1])];

alert(chkDat(usdat,eudat); //=> true
alert(eudat.join('-'));    //=> '2011-05-19'

function chkDat(orig,eu){
   var eu = new Date(eu.join('/'));
   return   eu.getMonth()+1 === parseInt(orig[0],10)
         && eu.getDate() === parseInt(orig[1],10)
         && eu.getFullYear() === parseInt(orig[2],10)
   ;
}

Note the date format you're after is called Calendar date ( ISO 8601 ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM