我想知道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检查了一下,这种行为符合标准,这正是我所要的。


当前回答

此函数以字符分隔的数字格式验证字符串日期,例如dd/mm/yyyy、mm/dd/yyyy

/*
Param  : 
1)the date in string data type 
2)[optional - string - default is "/"] the date delimiter, most likely "/" or "-"
3)[optional - int - default is 0] the position of the day component when the date string is broken up via the String.split function (into arrays)
4)[optional - int - default is 1] the position of the month component when the date string is broken up via the String.split function (into arrays)
5)[optional - int - default is 2] the position of the year component when the date string is broken up via the String.split function (into arrays)

Return : a javascript date is returned if the params are OK else null
*/
function IsValidDate(strDate, strDelimiter, iDayPosInArray, iMonthPosInArray, iYearPosInArray) {
    var strDateArr; //a string array to hold constituents day, month, and year components
    var dtDate; //our internal converted date
    var iDay, iMonth, iYear;


    //sanity check 
    //no integer checks are performed on day, month, and year tokens as parsing them below will result in NaN if they're invalid
    if (null == strDate || typeof strDate != "string")
        return null;

    //defaults
    strDelimiter = strDelimiter || "/";
    iDayPosInArray = undefined == iDayPosInArray ? 0 : iDayPosInArray;
    iMonthPosInArray = undefined == iMonthPosInArray ? 1 : iMonthPosInArray;
    iYearPosInArray = undefined == iYearPosInArray ? 2 : iYearPosInArray;

    strDateArr = strDate.split(strDelimiter);

    iDay = parseInt(strDateArr[iDayPosInArray],10);
    iMonth = parseInt(strDateArr[iMonthPosInArray],10) - 1; // Note: months are 0-based
    iYear = parseInt(strDateArr[iYearPosInArray],10);

    dtDate = new Date(
        iYear,
        iMonth, // Note: months are 0-based
        iDay);

    return (!isNaN(dtDate) && dtDate.getFullYear() == iYear && dtDate.getMonth() == iMonth && dtDate.getDate() == iDay) ? dtDate : null; // Note: months are 0-based
}

示例调用:

var strDate="18-01-1971";

if (null == IsValidDate(strDate)) {

  alert("invalid date");
}

其他回答

当我尝试验证日期(如2012年2月31日)时,这些答案都不适用(在Safari 6.0中测试),然而,当尝试任何大于31的日期时,它们都可以正常工作。

所以我不得不用蛮力。假设日期的格式为mm/dd/yyyy。我正在使用@broox答案:

Date.prototype.valid = function() {
    return isFinite(this);
}    

function validStringDate(value){
    var d = new Date(value);
    return d.valid() && value.split('/')[0] == (d.getMonth()+1);
}

validStringDate("2/29/2012"); // true (leap year)
validStringDate("2/29/2013"); // false
validStringDate("2/30/2012"); // false

为什么我建议moment.js

这是非常受欢迎的图书馆

简单地解决所有日期和时间、格式和时区问题

易于检查字符串日期是否有效

var date = moment("2016-10-19");
date.isValid()

我们无法解决验证所有案例的简单方法

分歧

如果我插入有效数字,如89,90,95英寸new Date()在几个应答器上,我得到了坏结果,但它返回真

常量isValidDate=date=>{console.log('input'+date)var date=新日期(日期);console.log(日期)回来(Object.product.toString.call(date)==“[Object date]”&&+date)//返回!isNaN(date.getTime())}var test=“2012年4月5日”console.log(isValidDate(测试))var测试=“95”console.log(isValidDate(测试))var测试=“89”console.log(isValidDate(测试))var测试=“80”console.log(isValidDate(测试))var test=“badstring”console.log(isValidDate(测试))

function isValidDate(strDate) {
    var myDateStr= new Date(strDate);
    if( ! isNaN ( myDateStr.getMonth() ) ) {
       return true;
    }
    return false;
}

这样说吧

isValidDate(""2015/5/2""); // => true
isValidDate(""2015/5/2a""); // => false

我看到了一些与这个小片段非常接近的答案。

JavaScript方式:

函数isValidDate(dateObject){return new Date(dateObject).toString()!=='无效日期';}console.log(isValidDate('WTH'));//->假的console.log(isValidDate(新日期('WTH')));//->假的console.log(isValidDate(new Date()));//->真的

ES2015方式:

const isValidDate=dateObject=>新日期(dateObject).toString()!=='无效日期';console.log(isValidDate('WTH'));//->假的console.log(isValidDate(新日期('WTH')));//->假的console.log(isValidDate(new Date()));//->真的

我真的很喜欢克里斯托夫的方法(但没有足够的声誉来投票支持)。对于我的用途,我知道我将始终有一个Date对象,所以我只是用valid()方法扩展了日期。

Date.prototype.valid = function() {
  return isFinite(this);
}

现在我可以写这个了,它比在代码中检查isFinite更具描述性。。。

d = new Date(userDate);
if (d.valid()) { /* do stuff */ }