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


您应该使用:

var timestamp = Date.parse('foo');

if (isNaN(timestamp) == false) {
  var d = new Date(timestamp);
}

Date.parse()返回一个时间戳,一个整数表示自1970年1月1日以来的毫秒数。如果无法解析提供的日期字符串,它将返回NaN。


我会这样做:

if (Object.prototype.toString.call(d) === "[object Date]") {
  // it is a date
  if (isNaN(d)) { // d.getTime() or d.valueOf() will also work
    // date object is not valid
  } else {
    // date object is valid
  }
} else {
  // not a date object
}

更新〔2018-05-31〕:如果您不关心来自其他JS上下文(外部窗口、框架或iframe)的Date对象,则可以使用更简单的形式:

function isValidDate(d) {
  return d instanceof Date && !isNaN(d);
}

更新[2021-02-01]:请注意,“无效日期”(2013-13-32)和“无效日期对象”(new date('fo'))之间存在根本区别。只有当date实例有效时,此答案才处理验证日期输入。


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

d instanceof Date && isFinite(d)

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

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

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


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

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

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

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

我根据Borgar的解决方案编写了以下解决方案。包含在我的辅助函数库中,现在看起来像这样:

Object.isDate = function(obj) {
/// <summary>
/// Determines if the passed object is an instance of Date.
/// </summary>
/// <param name="obj">The object to test.</param>

    return Object.prototype.toString.call(obj) === '[object Date]';
}

Object.isValidDate = function(obj) {
/// <summary>
/// Determines if the passed object is a Date object, containing an actual date.
/// </summary>
/// <param name="obj">The object to test.</param>

    return Object.isDate(obj) && !isNaN(obj.getTime());
}

// check whether date is valid
var t = new Date('2011-07-07T11:20:00.000+00:00x');
valid = !isNaN(t.valueOf());

我认为这是一个漫长的过程。我们可以简化如下:

 function isValidDate(dateString) {
        debugger;
        var dateStringSplit;
        var formatDate;

        if (dateString.length >= 8 && dateString.length<=10) {
            try {
                dateStringSplit = dateString.split('/');
                var date = new Date();
                date.setYear(parseInt(dateStringSplit[2]), 10);
                date.setMonth(parseInt(dateStringSplit[0], 10) - 1);
                date.setDate(parseInt(dateStringSplit[1], 10));

                if (date.getYear() == parseInt(dateStringSplit[2],10) && date.getMonth()+1 == parseInt(dateStringSplit[0],10) && date.getDate() == parseInt(dateStringSplit[1],10)) {
                    return true;
                }
                else {
                    return false;
                }

            } catch (e) {
                return false;
            }
        }
        return false;
    }

受到Borgar方法的启发,我确保代码不仅验证了日期,而且实际上确保了日期是真实的日期,这意味着2011年9月31日和2011年2月29日这样的日期是不允许的。

function(dateStr) {
  s = dateStr.split('/');
  d = new Date(+s[2], s[1] - 1, +s[0]);
  if (Object.prototype.toString.call(d) === "[object Date]") {
    if (!isNaN(d.getTime()) && d.getDate() == s[0] &&
      d.getMonth() == (s[1] - 1)) {
      return true;
    }
  }
  return "Invalid date!";
}

我使用以下代码验证年、月和日期的值。

function createDate(year, month, _date) {
  var d = new Date(year, month, _date);
  if (d.getFullYear() != year 
    || d.getMonth() != month
    || d.getDate() != _date) {
    throw "invalid date";
  }
  return d;
}

有关详细信息,请参阅javascript中的检查日期


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

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

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

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

上述解决方案对我来说都不起作用,但起作用的是

function validDate (d) {
    var date = new Date(d);
    var day = "" + date.getDate();
    if ( day.length == 1 ) day = "0" + day;
    var month = "" + (date.getMonth() + 1);
    if ( month.length == 1 ) month = "0" + month;
    var year = "" + date.getFullYear();
    return (( month + "/" + day + "/" + year ) == d );
}

上面的代码将在JS将2012年2月31日更改为2012年3月2日时看到它是无效的


当我尝试验证日期(如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

我的解决方案是简单地检查您是否获得了有效的日期对象:

实施

Date.prototype.isValid = function () {
    // An invalid date object returns NaN for getTime() and NaN is the only
    // object not strictly equal to itself.
    return this.getTime() === this.getTime();
};  

用法

var d = new Date("lol");

console.log(d.isValid()); // false

d = new Date("2012/09/11");

console.log(d.isValid()); // true

IsValidDate: function(date) {
        var regex = /\d{1,2}\/\d{1,2}\/\d{4}/;
        if (!regex.test(date)) return false;
        var day = Number(date.split("/")[1]);
        date = new Date(date);
        if (date && date.getDate() != day) return false;
        return true;
}

我想提到的是,jQueryUIDatePicker小部件有一个非常好的日期验证器实用程序方法,可以检查格式和有效性(例如,不允许2013年1月33日的日期)。

即使您不想将页面上的datepicker小部件用作UI元素,也可以始终将其.js库添加到页面中,然后调用验证器方法,将要验证的值传递给它。

参见:http://api.jqueryui.com/datepicker/

它没有被列为一种方法,但它是作为一种实用函数存在的。在页面中搜索“parsedate”,您会发现:

$.datepicker.parseDate(格式、值、设置)-从具有指定格式的字符串值中提取日期。

示例用法:

var stringval = '01/03/2012';
var testdate;

try {
  testdate = $.datepicker.parseDate('mm/dd/yy', stringval);
             // Notice 'yy' indicates a 4-digit year value
} catch (e)
{
 alert(stringval + ' is not valid.  Format must be MM/DD/YYYY ' +
       'and the date value must be valid for the calendar.';
}

(有关指定日期格式的详细信息,请参阅http://api.jqueryui.com/datepicker/#utility-parseDate)

在上面的示例中,您不会看到警报消息,因为“01/03/2012”是指定格式的日历有效日期。但是,例如,如果将“stringval”设置为“13/04/2013”,则会收到警告消息,因为值“13/04/13”不是日历有效值。

如果成功解析了传入的字符串值,“testdate”的值将是表示传入字符串值的Javascript Date对象。如果没有,它将是未定义的。


日期对象到字符串是检测两个字段是否为有效日期的更简单可靠的方法。例如,如果在日期输入字段中输入此“-------”。上面的一些答案行不通。

jQuery.validator.addMethod("greaterThan", 

    function(value, element, params) {
        var startDate = new Date($(params).val());
        var endDate = new Date(value);

        if(startDate.toString() === 'Invalid Date' || endDate.toString() === 'Invalid Date') {
            return false;
        } else {
            return endDate > startDate;
        }
    },'Must be greater than {0}.');

您可以简单地使用moment.js

下面是一个示例:

var m = moment('2015-11-32', 'YYYY-MM-DD');
m.isValid(); // false

文档中的验证部分非常清楚。

此外,以下解析标志会导致无效日期:

溢出:日期字段的溢出,例如第13个月、一个月的第32天(或非闰年的2月29日)、一年的第367天等。溢出包含与#invalidAt匹配的无效单位的索引(见下文)-1表示无溢出。invalidMonth:无效的月份名称,例如moment('Marbruary','MMM');。包含无效的月份字符串本身,否则为空。空:不包含任何可解析内容的输入字符串,例如moment(“这是无意义的”);。布尔值。等


资料来源:http://momentjs.com/docs/


对于日期的基于int 1的成分:

var is_valid_date = function(year, month, day) {
    var d = new Date(year, month - 1, day);
    return d.getFullYear() === year && (d.getMonth() + 1) === month && d.getDate() === day
};

测验:

    is_valid_date(2013, 02, 28)
&&  is_valid_date(2016, 02, 29)
&& !is_valid_date(2013, 02, 29)
&& !is_valid_date(0000, 00, 00)
&& !is_valid_date(2013, 14, 01)

您可以将日期和时间转换为毫秒getTime()

此getTime()方法在无效时返回Not a Number NaN

if(!isNaN(new Date("2012/25/255").getTime()))
  return 'valid date time';
  return 'Not a valid date time';

这对我很有效

new Date('foo') == 'Invalid Date'; //is true

然而,这并不奏效

new Date('foo') === 'Invalid Date'; //is false

var isDate_ = function(input) {
        var status = false;
        if (!input || input.length <= 0) {
          status = false;
        } else {
          var result = new Date(input);
          if (result == 'Invalid Date') {
            status = false;
          } else {
            status = true;
          }
        }
        return status;
      }

我已经编写了这个函数。给它传递一个字符串参数,它将根据格式“dd/MM/yyyy”确定它是否为有效日期。

这是一个测试

输入:“哈哈哈”,输出:false。

输入:“29/2/2000”,输出:true。

输入:“29/2/2001”,输出:false。

function isValidDate(str) {
    var parts = str.split('/');
    if (parts.length < 3)
        return false;
    else {
        var day = parseInt(parts[0]);
        var month = parseInt(parts[1]);
        var year = parseInt(parts[2]);
        if (isNaN(day) || isNaN(month) || isNaN(year)) {
            return false;
        }
        if (day < 1 || year < 1)
            return false;
        if(month>12||month<1)
            return false;
        if ((month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) && day > 31)
            return false;
        if ((month == 4 || month == 6 || month == 9 || month == 11 ) && day > 30)
            return false;
        if (month == 2) {
            if (((year % 4) == 0 && (year % 100) != 0) || ((year % 400) == 0 && (year % 100) == 0)) {
                if (day > 29)
                    return false;
            } else {
                if (day > 28)
                    return false;
            }      
        }
        return true;
    }
}

选择的答案很好,我也在使用它。然而,如果您正在寻找一种验证用户日期输入的方法,您应该知道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实例(此处为基准)具有有效日期(此处为基准)

结果如下:

function isValidDate(input) {
  if(!(input && input.getTimezoneOffset && input.setUTCFullYear))
    return false;

  var time = input.getTime();
  return time === time;
};

此函数以字符分隔的数字格式验证字符串日期,例如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");
}

通常,我会坚持浏览器堆栈中的任何Date植入。这意味着在本回复日期之前,在Chrome、Firefox和Safari中调用toDateString()时,您将始终得到“无效日期”。

if(!Date.prototype.isValidDate){
  Date.prototype.isValidDate = function(){
    return this.toDateString().toLowerCase().lastIndexOf('invalid') == -1;
  };
}

我没有在IE中测试这个。


function isValidDate(date) {
  return !! (Object.prototype.toString.call(date) === "[object Date]" && +date);
}

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

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

angular.isDate(myDate);

这种类型的isValidDate使用一个处理闰年的正则表达式。它适用于常规日期,但不适用于iso日期:

函数isValidDate(值){return/((^(10|12|0?[13578])([/])(3[01]|[12][0-9]|0?[1-9])([/])((1[8-9]\d{2})|([2-9]\d{3}))$)|(^(11|0?[469])([/])(30|[12][0-9]|0?[1-9])([/】)((1[8-9]\d{2})| 2)([/])(2[0-8]|1[0-9]|0?[1-9])([/])((1[8-9]\d{2})|([2-9]\d{3})$)|(^(0?2)([/])(29)1][89][0][48])$)|(^(0?2)([/])(29)([/])([2-9][0-9][0][48])$)|(^(0?2)([/])(29)([/])([1][89][2468][048])$)| 13579][26])$)/测试(值)}功能测试(值){console.log(`${value}有效:${isValidDate(value)}`)}<buttonClick=“test('fo')”>foo</button><button on单击=“测试('2/20/2000')”>2/20/2000</button><button on单击=“测试('20/2/2000')”>20/2/2000</button><button单击=“测试('2022-02-02T18:51:53.517Z')”>2022-02-01T18:51:535.17Z</button>


检查有效日期的最短答案

if(!isNaN(date.getTime()))

Date.valid = function(str){
  var d = new Date(str);
  return (Object.prototype.toString.call(d) === "[object Date]" && !isNaN(d.getTime()));
}

https://gist.github.com/dustinpoissant/b83750d8671f10c414b346b16e290ecf


基于顶级答案的就绪功能:

  /**
   * Check if date exists and is valid.
   *
   * @param {String} dateString Date in YYYY-mm-dd format.
   */
  function isValidDate(dateString) {
  var isValid = false;
  var date;

  date =
    new Date(
      dateString);

  if (
    Object.prototype.toString.call(
      date) === "[object Date]") {

    if (isNaN(date.getTime())) {

      // Date is unreal.

    } else {
      // Date is real if month and day match each other in date and string (otherwise may be shifted):
      isValid =
        date.getUTCMonth() + 1 === dateString.split("-")[1] * 1 &&
        date.getUTCDate() === dateString.split("-")[2] * 1;
    }
  } else {
    // It's not a date.
  }

  return isValid;
}

date.parse(valueToBeTested)>0是所有需要的。有效的日期将返回历元值,无效的值将返回NaN,由于不是数字,NaN将无法通过>0测试。

这是如此简单,以至于助手函数不会保存代码,尽管它可能更可读。如果你想要一个:

String.prototype.isDate = function() {
  return !Number.isNaN(Date.parse(this));
}

OR

要使用:

"StringToTest".isDate();

所以我喜欢@Ask Clarke的回答,通过为无法通过var d=new Date(d)的日期添加try-catch块,几乎没有什么改进-

function checkIfDateNotValid(d) {
        try{
            var d = new Date(d);
            return !(d.getTime() === d.getTime()); //NAN is the only type which is not equal to itself.
        }catch (e){
            return true;
        }

    }

这里已经有太多复杂的答案,但简单的一行就足够了(ES5):

Date.prototype.isValid = function (d) { return !isNaN(Date.parse(d)) } ;

或甚至在ES6中:

Date.prototype.isValid = d => !isNaN(Date.parse(d));

Date.prototype.toISOString在无效日期引发RangeError(至少在Chromium和Firefox中)。您可以使用它作为一种验证方法,并且可能不需要isValidDate(EAFP)。否则:

function isValidDate(d)
{
  try
  {
    d.toISOString();
    return true;
  }
  catch(ex)
  {
    return 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()));//->真的


检查日期是否为有效日期对象的另一种方法:

const isValidDate = (date) => 
  typeof date === 'object' && 
  typeof date.getTime === 'function' && 
  !isNaN(date.getTime())

简单优雅的解决方案:

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()中显示的日期不正确


尝试以下操作:

if (!('null' === JSON.stringify(new Date('wrong date')))) console.log('correct');
else console.log('wrong');

如果使用iots,则可以直接使用解码器DateFromISOString。

import { DateFromISOString } from 'io-ts-types/lib/DateFromISOString'

const decoded = DateFromISOString.decode('2020-05-13T09:10:50.957Z')

还没有人提到它,所以符号也是一种方法:

Symbol.for(new Date("Peter")) === Symbol.for("Invalid Date") // true

Symbol.for(new Date()) === Symbol.for("Invalid Date") // false

console.log('Symbol.for(新日期(“Peter”))===Symbol.ffor(“无效日期”)',Symbol.fo(新日期)===符号.for(“无效时间”))//trueconsole.log('Symbol.for(new Date())==Symbol.ffor(“无效日期”)',Symbol.fo(newDate()==符号.for(“无效时间”))//false

注意:https://caniuse.com/#search=Symbol


纯JavaScript解决方案:

const date = new Date(year, (+month-1), day);
const isValidDate = (Boolean(+date) && date.getDate() == day);

也适用于闰年!

贷方至https://medium.com/@esganzerla/simple-date-validation-with-javascript-caea0f71883c


为什么我建议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(测试))


我有一个解决办法。

const isInvalidDate = (dateString) => JSON.stringify(new Date(dateString)) === 'null';

const invalidDate = new Date('Hello');
console.log(isInvalidDate(invalidDate)); //true

const validDate = new Date('2021/02/08');
console.log(isInvalidDate(validDate)); //false

在这么多人在我面前尝试之后,我为什么要写第48个答案?大多数答案部分正确,不会在任何情况下都有效,而其他答案则是不必要的冗长和复杂。下面是一个非常简洁的解决方案。这将检查它是否为日期类型,然后检查有效的日期对象:

return x instanceof Date && !!x.getDate();

现在来解析日期文本:大多数解决方案都使用date.parse()或“new date()”——这两种方法都会在某些情况下失败,而且可能很危险。JavaScript解析多种格式,并且依赖于本地化。例如,像“1”和“blah-123”这样的字符串将解析为有效日期。

还有一些帖子要么使用大量代码,要么使用一英里长的RegEx,要么使用第三方框架。

这是验证日期字符串的非常简单的方法。

函数isDate(txt){var matches=txt.match(/^\d?\d\/(\d?\d)\/\d{4}$/)//注:RegEx中的“日”用括号括起来回来匹配&&!!Date.parse(txt)&&newDate(txt).getDate()==匹配[1];}测试功能<br/><br/><input id=“dt”value=“12/21/2020”><input type=“button”value=“validate”id=“btnAction”onclick=“document.getElementById('slt').innerText=isDate(document.getElement ById('dt').value)”><br/><br/>结果:<span id=“rslt”></span>

isDate的第一行使用简单的RegEx解析输入文本,以验证日期格式mm/dd/yyyy或m/d/yyyy。对于其他格式,您需要相应地更改RegEx,例如,对于dd-mm-yyyy,RegEx变为/^(\d?\d)-\d?\d-\d{4}$/

如果解析失败,“matches”为空,否则将存储月份的日期。第二行进行了更多测试,以确保它是有效日期,并消除了类似2021 9月31日(JavaScript允许)的情况。最后请注意,double-back(!!)将“falsy”转换为布尔值false。


我很少推荐没有的图书馆。但考虑到目前为止的大量答案,似乎值得指出的是,流行的库“date fns”有一个函数isValid。以下文件摘自其网站:

isValid argument Before v2.0.0 v2.0.0 onward
new Date() true true
new Date('2016-01-01') true true
new Date('') false false
new Date(1488370835081) true true
new Date(NaN) false false
'2016-01-01' TypeError false
'' TypeError false
1488370835081 TypeError true
NaN TypeError false

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

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

要测试无效日期:

isNaN(date)

要测试有效日期:

!isNaN(date)

或(感谢icc97提供此选项)

isFinite(date) 

或打字稿(感谢pat migliaccio)

isFinite(+date) 

对于日期FNS,有一个名为isExists的函数。它检查日期是否存在(2月31日不应存在)。

示例:

// For the valid date:
const result = isExists(2018, 0, 31)
//=> true
// For the invalid date:
const result = isExists(2018, 1, 31) 
//=> false

文档:https://date-fns.org/v2.28.0/docs/isExists


这里只有少数人(@Zen、@Dex、@wanglab……)对javascript容忍在2月、4月、6月等月份溢出日数。。。

如果指定要处理的格式(即yyyy-MM-dd),则在解决方案中根本不必使用javascript对象Date。

函数leapYear(年){return((年%4==0)&&(年%100!=0))||(年%400==0);}函数validateStr(dateStr){if(/^[0-9][0-9][0-9][0-9][0-9]-[0-9][9-9]-[0-9][0-9][0-9]$/.test(dateStr)==false){return false;}var m=parseInt(dateStr.substr(5,2));var d=parseInt(dateStr.substr(8,2));var y=parseInt(dateStr.substr(0,4));//您可以为大于5000:-D的值添加年度检查如果(m>12||d>31){return false;}否则,如果(m==2&&d>28){如果(d==29){if(!leapYear(y)){return false;}}其他{return false;}}否则如果(d>30&&(m==4||m==6||m==9||m===11)){return false;}返回true;}console.log(“2020-02-29:”+validateDateStr(“2020:02-29”));//真的console.log(“2020-02-30:”+validateDateStr(“2020:02-30”));//假的console.log(“2022-02-29:”+validateDateStr(“20202-02-29”));//假的console.log(“2021-02-28:”+validateDateStr(“2011-02-28”));//真的console.log(“2020-03-31:”+validateDateStr(“2020:03-31”));//真的console.log(“2020-04-30:”+validateDateStr(“2020:04-30”));//真的console.log(“2020-04-31:”+validateDateStr(“2020:04-31”));//假的console.log(“2020-07-31:”+validateDateStr(“2020:07-31”));//真的console.log(“2020-07-32:”+validateDateStr(“2020:07-32”));//假的控制台日志(“2020-08-31:”+validateDateStr(“2020:08-31”));//真的console.log(“2020-12-03:”+validateDateStr(“2020-102-03”));//真的console.log(“2020-13-03:”+validateDateStr(“2020-103-03”));//假的console.log(“0020-12-03:”+validateDateStr(“0020-102-03”));//真的//无效正则表达式console.log(“20-12-03:”+validateDateStr(“20-12-103”));//假的console.log(“2020-012-03:”+validateDateStr(“2020:012-03”));//假的console.log(“2020-12-003:”+validateDateStr(“2020-102-003”));//假的


NaN是假的。invalidDateObject.valueOf()为NaN。

const d = new Date('foo');
if (!d.valueOf()) {
  console.error('Not a valid date object');
}
else {
  // act on your validated date object
}

尽管valueOf()在功能上等同于getTime(),但我觉得在这种情况下更合适。