来自:5/19/2011
至:2011-05-19
当它发现它不像5/40/2011
那样真实时,我需要它来引发错误。是否有任何库可以做得好?
答案 0 :(得分:5)
也许这不是最佳解决方案,但你可以尝试这样简单的方法:
var from="5/19/2011";
var temp = from.split("/");
var to = temp[2] + "-" + temp[0] + "-" + temp[1];
答案 1 :(得分:2)
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
返回值 {Date} Date对象,如果无法将字符串转换为Date,则返回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
返回值 {Boolean}如果在范围内,则为true,否则为false。
答案 2 :(得分:1)
保持简单:
[编辑],你也想要一张支票,所以添加了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)
;
}
注意您所关注的日期格式称为日历日期(ISO 8601)。