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

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


当前回答

是否可以检查一个日期相关的函数是可用的对象,以发现它是否是一个日期对象?

就像

var l = new Date();
var isDate = (l.getDate !== undefined) ? true; false;

其他回答

Date.parse()是否足够?

请参阅其相关MDN文档页面。

日期。如果字符串date有效,Parse返回时间戳。下面是一些用例:

// /!\ from now (2021) date interpretation changes a lot depending on the browser
Date.parse('01 Jan 1901 00:00:00 GMT') // -2177452800000
Date.parse('01/01/2012') // 1325372400000
Date.parse('153') // NaN (firefox) -57338928561000 (chrome)
Date.parse('string') // NaN
Date.parse(1) // NaN (firefox) 978303600000 (chrome)
Date.parse(1000) // -30610224000000 from 1000 it seems to be treated as year
Date.parse(1000, 12, 12) // -30610224000000 but days and month are not taken in account like in new Date(year, month,day...)
Date.parse(new Date(1970, 1, 0)) // 2588400000
// update with edge cases from comments
Date.parse('4.3') // NaN (firefox) 986248800000 (chrome)
Date.parse('2013-02-31') // NaN (firefox) 1362268800000 (chrome)
Date.parse("My Name 8") // NaN (firefox) 996616800000 (chrome)

我知道这是一个老问题,但我遇到了同样的问题,发现没有一个答案能正常工作——特别是从日期中剔除数字(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”));

像这样的怎么样?它将测试它是一个Date对象还是一个日期字符串:

function isDate(value) {
    var dateFormat;
    if (toString.call(value) === '[object Date]') {
        return true;
    }
    if (typeof value.replace === 'function') {
        value.replace(/^\s+|\s+$/gm, '');
    }
    dateFormat = /(^\d{1,4}[\.|\\/|-]\d{1,2}[\.|\\/|-]\d{1,4})(\s*(?:0?[1-9]:[0-5]|1(?=[012])\d:[0-5])\d\s*[ap]m)?$/;
    return dateFormat.test(value);
}

我应该提到的是,这并不测试ISO格式的字符串,但只要再对RegExp做一些工作,您就可以了。

该函数验证格式为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;
}

我就是这么做的。这不会涵盖所有格式。 你必须相应地调整。我可以控制格式,所以它适合我

function isValidDate(s) {
            var dt = "";
            var bits = [];
            if (s && s.length >= 6) {
                if (s.indexOf("/") > -1) {
                    bits = s.split("/");
                }
                else if (s.indexOf("-") > -1) {
                    bits = s.split("-");
                }
                else if (s.indexOf(".") > -1) {
                    bits = s.split(".");
                }
                try {
                    dt = new Date(bits[2], bits[0] - 1, bits[1]);
                } catch (e) {
                    return false;
                }
                return (dt.getMonth() + 1) === parseInt(bits[0]);
            } else {
                return false;
            }
        }