jQuery 中有 isDate
函数吗?
如果输入是日期,则应返回 true
,否则返回 false
。
最佳答案
如果您不想处理外部库,一个简单的纯 JavaScript 解决方案是:
function isDate(val) {
var d = new Date(val);
return !isNaN(d.valueOf());
}
<小时/>
更新: !!主要警告!!
@BarryPicker 在评论中提出了一个很好的观点。对于所有非闰年,JavaScript 会自动将 2 月 29 日转换为 3 月 1 日。此行为似乎严格限于 31 日之前的天(例如,3 月 32 日不会转换为 4 月 1 日,但 6 月 31 日会转换为 7 月 1 日)。根据您的情况,这可能是您可以接受的限制,但您应该意识到这一点:
>>> new Date('2/29/2014')
Sat Mar 01 2014 00:00:00 GMT-0500 (Eastern Standard Time)
>>> new Date('3/32/2014')
Invalid Date
>>> new Date('2/29/2015')
Sun Mar 01 2015 00:00:00 GMT-0500 (Eastern Standard Time)
>>> isDate('2/29/2014')
true // <-- no it's not true! 2/29/2014 is not a valid date!
>>> isDate('6/31/2015')
true // <-- not true again! Apparently, the crux of the problem is that it
// allows the day count to reach "31" regardless of the month..
关于javascript - 如何确定给定字符串是否代表日期?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3880615/