Javascript 检测字符串是否可以转换为日期
目前,我正在使用:Javascript 检测字符串是否可以转换为日期,javascript,datetime,date,Javascript,Datetime,Date,目前,我正在使用: var d = new Date("March 7 2012"); document.write(d.getMonth() + 1); 如果日期字符串有点奇怪,比如No date,例如: var d = new Date("No Date"); // anything which isn't recognisable as a date document.write(d.getMonth() + 1); 这里我得到的输出是NaN 如果发生类似情况,如何显示更好的消息您可以
var d = new Date("March 7 2012");
document.write(d.getMonth() + 1);
如果日期字符串有点奇怪,比如No date
,例如:
var d = new Date("No Date"); // anything which isn't recognisable as a date
document.write(d.getMonth() + 1);
这里我得到的输出是NaN
如果发生类似情况,如何显示更好的消息您可以使用
isNaN
检查值是否为NaN
:
if (isNaN(d.getMonth())) {
//value is not a date
}
else
{
document.write(d.getMonth() + 1);
}
您可以使用
isNaN
检查值是否为NaN
:
if (isNaN(d.getMonth())) {
//value is not a date
}
else
{
document.write(d.getMonth() + 1);
}
用这样的东西
var d= new Date('No Date');
var mon=d.getMonth()+1;
document.write(isNAN(mon)?"No Date": mon);
用这样的东西
var d= new Date('No Date');
var mon=d.getMonth()+1;
document.write(isNAN(mon)?"No Date": mon);
您也可以这样做:
Date.isValid = function(date) {
return !!Date.parse(date);
};
Date.isValid('fake') // false
Date.isValid('1990-11-15T00:00:00+00:00') // true
您也可以这样做:
Date.isValid = function(date) {
return !!Date.parse(date);
};
Date.isValid('fake') // false
Date.isValid('1990-11-15T00:00:00+00:00') // true
这似乎奏效了
new Date("Hi") == 'Invalid Date'
这似乎奏效了
new Date("Hi") == 'Invalid Date'
可能重复的可能重复的否决票,因为这不起作用?因为它不总是准确而否决投票?或者只是因为你想否决某个人?因为这不起作用而否决?因为它不总是准确而否决投票?或者仅仅因为你想投票否决某个人?