我想知道JS中有效日期对象和无效日期对象之间的区别,但无法弄清楚:

var d = new Date("foo");
console.log(d.toString()); // shows 'Invalid Date'
console.log(typeof d); // shows 'object'
console.log(d instanceof Date); // shows 'true'

编写isValidDate函数有什么想法吗?

Ash建议使用Date.parse来解析日期字符串,这提供了一种权威的方法来检查日期字符串是否有效。如果可能的话,我更希望我的API接受Date实例,并能够检查/断言它是否有效。Borgar的解决方案做到了这一点,但我需要在浏览器上进行测试。我还想知道是否有更优雅的方式。Ash让我考虑不让我的API接受Date实例,这是最容易验证的。Borgar建议测试Date实例,然后测试Date的时间值。如果日期无效,则时间值为NaN。我用ECMA-262检查了一下,这种行为符合标准,这正是我所要的。


当前回答

在阅读了迄今为止的所有答案后,我将提供最简单的答案。

这里的每个解决方案都提到调用date.getTime()。然而,这是不需要的,因为从date到Number的默认转换是使用getTime()值。是的,你的打字检查会有问题OP明确知道他们有一个Date对象,所以也不需要测试。

要测试无效日期:

isNaN(date)

要测试有效日期:

!isNaN(date)

或(感谢icc97提供此选项)

isFinite(date) 

或打字稿(感谢pat migliaccio)

isFinite(+date) 

其他回答

选择的答案很好,我也在使用它。然而,如果您正在寻找一种验证用户日期输入的方法,您应该知道date对象非常持久地将看似无效的构造参数转换为有效的构造参数。以下单元测试代码说明了这一点:

QUnit.test( "valid date test", function( assert ) {
  //The following are counter-examples showing how the Date object will 
  //wrangle several 'bad' dates into a valid date anyway
  assert.equal(isValidDate(new Date(1980, 12, 15)), true);
  d = new Date();
  d.setFullYear(1980);
  d.setMonth(1);
  d.setDate(33);
  assert.equal(isValidDate(d), true);
  assert.equal(isValidDate(new Date(1980, 100, 150)), true);
  //If you go to this exterme, then the checker will fail
  assert.equal(isValidDate(new Date("This is junk")), false);
  //This is a valid date string
  assert.equal(isValidDate(new Date("November 17, 1989")), true);
  //but is this?
  assert.equal(isValidDate(new Date("November 35, 1989")), false);  
  //Ha!  It's not.  So, the secret to working with this version of 
  //isValidDate is to pass in dates as text strings... Hooboy
  //alert(d.toString());
});

您可以通过以下方式检查Date对象d的有效性

d instanceof Date && isFinite(d)

为了避免跨帧问题,可以用

Object.prototype.toString.call(d) === '[object Date]'

在Borgar的回答中调用getTime()是不必要的,因为isNaN()和isFinite()都隐式转换为数字。

您可以使用此scirpt检查txDate.value的有效格式。如果格式不正确,则Date obejct未实例化,并将null返回dt。

 var dt = new Date(txtDate.value)
 if (isNaN(dt))

正如@MiF简短地建议的那样

 if(isNaN(new Date(...)))

简单优雅的解决方案:

const date = new Date(`${year}-${month}-${day} 00:00`)
const isValidDate = (Boolean(+date) && date.getDate() == day)

来源:

[1] https://medium.com/@esganzerla/simple-date-validation-with-javascript-caea0f71883c

[2] JavaScript中new date()中显示的日期不正确

对于Angular.js项目,您可以使用:

angular.isDate(myDate);