如何确定给定字符串是否代表日期?

Kut*_*ith 18 javascript jquery

isDatejQuery中有一个函数吗?

true如果输入是日期,则应返回,false否则返回.

mwo*_*e02 35

如果您不想处理外部库,那么一个简单的仅限JavaScript的解决方案是:

function isDate(val) {
    var d = new Date(val);
    return !isNaN(d.valueOf());
}
Run Code Online (Sandbox Code Playgroud)

更新:!!主要警告!!
@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..
Run Code Online (Sandbox Code Playgroud)


小智 6

javascript中最简单的方法是:

function isDate(dateVal) {
  var d = new Date(dateVal);
  return d.toString() === 'Invalid Date'? false: true;
}
Run Code Online (Sandbox Code Playgroud)


iri*_*uzz 5

这取决于你如何努力实现这一点,您可以使用该"验证" jQuery插件使用date选项设置.