有什么简单的方法来检查一个值是否为有效日期,允许任何已知的日期格式。

例如,我有值10-11-2009、10/11/2009、2009-11-10T07:00:00+0000,这些值都应该被识别为日期值,而值200、10、350不应该被识别为日期值。如果可能的话,最简单的检查方法是什么?因为时间戳也是允许的。


当前回答

这里的答案都没有提到检查日期是否无效,例如2月31日。这个函数通过检查返回的月份是否等同于原来的月份,并确保提供了有效的年份来解决这个问题。

//expected input dd/mm/yyyy or dd.mm.yyyy or dd-mm-yyyy
function isValidDate(s) {
  var separators = ['\\.', '\\-', '\\/'];
  var bits = s.split(new RegExp(separators.join('|'), 'g'));
  var d = new Date(bits[2], bits[1] - 1, bits[0]);
  return d.getFullYear() == bits[2] && d.getMonth() + 1 == bits[1];
} 

其他回答

我知道这是一个老问题,但我遇到了同样的问题,发现没有一个答案能正常工作——特别是从日期中剔除数字(1,200,345等),这是最初的问题。这是我能想到的一个相当非正统的方法,它似乎有效。请指出是否有失败的情况。

if(sDate.toString() == parseInt(sDate).toString()) return false;

这一行是用来剔除数字的。因此,整个函数看起来像这样:

功能障碍(sDate) ( 如果(sDate.toString() == parseInt(sDate).toString()假返回; var tryDate =新日期(sDate); 回归(tryDate & tryDate.toString !=“NaN”& tryDate !=“Invalid Date”); ) 游戏机。log (" 100 ", isDate (100); 游戏机。log(“234”isDate(“234”); 游戏机。log (, isDate "你好"()"你好"); log控制台(“2018年2月25日”,“2018年2月25日”); 游戏机。log (2009-11-10T07:00:00 + 2”、“isDate(“2009-11-10T07:00:00 + 2”));

我觉得没有一个答案正确理解了OP的问题。这里的问题是JavaScript可以将任何数字解析为有效日期,因为date对象可以将'3000'这样的字符串解析为年份,并将返回一个有效的date实例:

new Date('3000')

> Wed Jan 01 3000 02:00:00 GMT+0200 (Eastern European Standard Time)

为了解决这个问题,我们可以在严格模式下通过传入第三个参数来使用Day.js库的解析方法。它被记录在他们的字符串+格式页面。为了使解析能够基于格式工作,我们还必须启用CustomParseFormat插件。我假设你可以在这里使用ESM导入,或者设置一个像Webpack这样的编译器

import dayjs from 'dayjs'
import formatParser from 'dayjs/plugin/customParseFormat'

dayjs.extend(formatParser)

dayjs('3000', 'YYYY-MM-DD', true).isValid()

> false

下面是可以用来验证输入是否为可以转换为日期对象的数字或字符串的方法。

它涵盖以下情况:

捕获任何导致“无效日期”日期构造函数结果的输入; 捕捉从技术角度来看日期是“有效的”,但从业务逻辑角度来看它是无效的情况,例如

new Date(null).getTime(): 0 new Date(true).getTime(): 1 new Date(-3.14).getTime(): -3 new Date(["1", "2"]).toDateString(): Tue Jan 02 2001 new Date([1,2]).toDateString(): Tue Jan 02 2001

function checkDateInputValidity(input, lowerLimit, upperLimit) {
    // make sure the input is a number or string to avoid false positive correct dates:
    if (...) {
        return false
    }
    // create the date object:
    const date = new Date(input)
    // check if the Date constructor failed:
    if (date.toDateString() === 'Invalid Date') {
        return false
    }
    // check if the Date constructor succeeded, but the result is out of range:
    if (date < new Date(lowerLimit) || date > new Date(upperLimit)) {
        return false
    }
    return true
}

// const low = '2021-12-31T23:59:59'
// const high = '2025-01-01T00:00:00'

该函数验证格式为m/d/yyyy或mm/dd/yyyy的输入字符串是否可以转换为日期,并且该日期是与输入字符串匹配的有效日期。添加更多条件检查来验证其他格式。

/**
 * Verify if a string is a date
 * @param {string} sDate - string that should be formatted m/d/yyyy or mm/dd/yyyy
 * @return {boolean} whether string is a valid date
 */
function isValidDate(sDate) {
  let newDate = new Date(sDate);
  console.log(sDate + " date conversion: " + newDate);
  let isDate = (!isNaN(newDate.getTime()));
  console.log(sDate + " is a date: " + isDate);
  if (isDate) {
    let firstSlash = sDate.indexOf("/");
    let secondSlash = sDate.indexOf("/",firstSlash+1);
    let originalDateString = parseInt(sDate.slice(0,firstSlash),10) + "/" + parseInt(sDate.slice(firstSlash+1,secondSlash),10) + "/" + parseInt(sDate.slice(secondSlash+1),10);
    let newDateString = (newDate.getMonth()+1) + "/" + (newDate.getDate()) + "/" + (newDate.getFullYear());
    isDate = (originalDateString == newDateString);
    console.log(originalDateString + " matches " + newDateString + ": " + isDate);
  }
  return isDate;
}

这里的答案都没有提到检查日期是否无效,例如2月31日。这个函数通过检查返回的月份是否等同于原来的月份,并确保提供了有效的年份来解决这个问题。

//expected input dd/mm/yyyy or dd.mm.yyyy or dd-mm-yyyy
function isValidDate(s) {
  var separators = ['\\.', '\\-', '\\/'];
  var bits = s.split(new RegExp(separators.join('|'), 'g'));
  var d = new Date(bits[2], bits[1] - 1, bits[0]);
  return d.getFullYear() == bits[2] && d.getMonth() + 1 == bits[1];
}