从:2011年5月19日
到:2011-05-19
当发现类似于5/40/2011
等不真实的日期时,我需要它引发一个错误。是否有任何良好的库可以做到这一点?
从:2011年5月19日
到:2011-05-19
当发现类似于5/40/2011
等不真实的日期时,我需要它引发一个错误。是否有任何良好的库可以做到这一点?
var from="5/19/2011";
var temp = from.split("/");
var to = temp[2] + "-" + temp[0] + "-" + temp[1];
那么Datejs这个开源日期库怎么样?具体来说:
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
返回值 {日期} 一个日期对象,如果字符串无法转换为日期,则返回 null。
或者
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
返回值 {布尔值} 如果在范围内则为true,否则为false。
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)
;
}
注意,你需要的日期格式被称为日历日期(ISO 8601)。