How to convert American date format to European

from: 5/19/2011

to: 2011-05-19

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

+4
source share
3 answers

What about open source datejs libraries? In particular:

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 to 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 

The return value {Boolean} is true if within the range, otherwise false.

+2
source

this may not be the best solution, but you can try a simple way:

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

Keep it simple:

[ edit ] correctly, you also need a check, so fn chkDat added:

 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 use is called the calendar date ( ISO 8601 ).

+1
source

All Articles