检查字符串是否为日期值

发布于 2024-12-05 03:08:28 字数 250 浏览 1 评论 0原文

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

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

What is an easy way to check if a value is a valid date, any known date format allowed.

For example I have the values 10-11-2009, 10/11/2009, 2009-11-10T07:00:00+0000 which should all be recognized as date values, and the values 200, 10, 350, which should not be recognized as a date value. What is the simplest way to check this, if this is even possible? Because timestamps would also be allowed.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(25

雾里花 2024-12-12 03:08:29

我会

var myDateStr= new Date("2015/5/2");

if( ! isNaN ( myDateStr.getMonth() )) {
    console.log("Valid date");
}
else {
    console.log("Invalid date");
}

这里播放

I would do this

var myDateStr= new Date("2015/5/2");

if( ! isNaN ( myDateStr.getMonth() )) {
    console.log("Valid date");
}
else {
    console.log("Invalid date");
}

Play here

未央 2024-12-12 03:08:29

这个可调用函数工作完美,对于有效日期返回 true。
请务必使用 ISO 格式的日期(yyyy-mm-dd 或 yyyy/mm/dd)进行调用:

function validateDate(isoDate) {

    if (isNaN(Date.parse(isoDate))) {
        return false;
    } else {
        if (isoDate != (new Date(isoDate)).toISOString().substr(0,10)) {
            return false;
        }
    }
    return true;
}

This callable function works perfectly, returns true for valid date.
Be sure to call using a date on ISO format (yyyy-mm-dd or yyyy/mm/dd):

function validateDate(isoDate) {

    if (isNaN(Date.parse(isoDate))) {
        return false;
    } else {
        if (isoDate != (new Date(isoDate)).toISOString().substr(0,10)) {
            return false;
        }
    }
    return true;
}
薄情伤 2024-12-12 03:08:29

检查对象是否可以使用与日期相关的函数来确定它是否是日期对象是否可以?

喜欢

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

is it fine to check for a Date related function is available for the object to find whether it is a Date object or not ?

like

var l = new Date();
var isDate = (l.getDate !== undefined) ? true; false;
药祭#氼 2024-12-12 03:08:29

我发现这个解决方案非常好:

const DateTime = require('luxon').DateTime;

isDateValid(stringDate) {
  let date = DateTime.fromFormat(stringDate, 'd-M-y');
  if (date.invalid === null) {
    return date.toJSDate();
  }
  date = DateTime.fromFormat(stringDate, 'd,M,y');
  if (date.invalid === null) {
    return date.toJSDate();
  }
  date = DateTime.fromFormat(stringDate, 'y-M-d');
  if (date.invalid === null) {
    return date.toJSDate();
  }
  date = DateTime.fromFormat(stringDate, 'y,M,d');
  if (date.invalid === null) {
    return date.toJSDate();
  }
  date = DateTime.fromFormat(stringDate, 'y.M.d');
  if (date.invalid === null) {
    return date.toJSDate();
  }
  date = DateTime.fromFormat(stringDate, 'd.M.y');
  if (date.invalid === null) {
    return date.toJSDate();
  }
  date = DateTime.fromFormat(stringDate, 'y/M/d');
  if (date.invalid === null) {
    return date.toJSDate();
  }
  date = DateTime.fromFormat(stringDate, 'd/M/y');
  if (date.invalid === null) {
    return date.toJSDate();
  }
  return false;
}

isDateValid('30.12.86'); //true
isDateValid('30/12/86'); //true
isDateValid('86-12-40'); //false

您可以轻松添加更多格式

i find this solution very good:

const DateTime = require('luxon').DateTime;

isDateValid(stringDate) {
  let date = DateTime.fromFormat(stringDate, 'd-M-y');
  if (date.invalid === null) {
    return date.toJSDate();
  }
  date = DateTime.fromFormat(stringDate, 'd,M,y');
  if (date.invalid === null) {
    return date.toJSDate();
  }
  date = DateTime.fromFormat(stringDate, 'y-M-d');
  if (date.invalid === null) {
    return date.toJSDate();
  }
  date = DateTime.fromFormat(stringDate, 'y,M,d');
  if (date.invalid === null) {
    return date.toJSDate();
  }
  date = DateTime.fromFormat(stringDate, 'y.M.d');
  if (date.invalid === null) {
    return date.toJSDate();
  }
  date = DateTime.fromFormat(stringDate, 'd.M.y');
  if (date.invalid === null) {
    return date.toJSDate();
  }
  date = DateTime.fromFormat(stringDate, 'y/M/d');
  if (date.invalid === null) {
    return date.toJSDate();
  }
  date = DateTime.fromFormat(stringDate, 'd/M/y');
  if (date.invalid === null) {
    return date.toJSDate();
  }
  return false;
}

isDateValid('30.12.86'); //true
isDateValid('30/12/86'); //true
isDateValid('86-12-40'); //false

and you can easily add more formats

巴黎盛开的樱花 2024-12-12 03:08:29

这是一个极简主义版本。

var isDate = function (date) {
    return!!(function(d){return(d!=='Invalid Date'&&!isNaN(d))})(new Date(date));
}

Here's a minimalist version.

var isDate = function (date) {
    return!!(function(d){return(d!=='Invalid Date'&&!isNaN(d))})(new Date(date));
}
鹿童谣 2024-12-12 03:08:29

好吧,这是一个老问题,但我在检查此处的解决方案时找到了另一个解决方案。对我来说,检查函数 getTime() 是否存在于日期对象中:

const checkDate = new Date(dateString);

if (typeof checkDate.getTime !== 'function') {
  return;
}

Ok, this is an old question, but I found another solution while checking the solutions here. For me works to check if the function getTime() is present at the date object:

const checkDate = new Date(dateString);

if (typeof checkDate.getTime !== 'function') {
  return;
}
好多鱼好多余 2024-12-12 03:08:29

我认为最直接的解决方案是

Date.parse(yourDate) > 0 ? true : false;

如果它不是有效日期,它将是 NaN,即大于 0。

I think the most straight forward solution would be

Date.parse(yourDate) > 0 ? true : false;

If it is not a valid date, it will be NaN, which is not greater than 0.

内心荒芜 2024-12-12 03:08:29

我相信这是仅包含数字的日期最简单的工作答案:

var rst = Date.parse(sDate.replaceAll(" ",""));
if(rst===NaN) console.log("not a date");
else console.log("a great date")

通过删除空格,您可以检测到诸如“hello 2”之类的值,这些值被视为日期。
对于包含日期名称或月份名称等字符串的日期......我相信这是关于字符串验证的。

I believe this is the simplest working answer for date that contains only numbers:

var rst = Date.parse(sDate.replaceAll(" ",""));
if(rst===NaN) console.log("not a date");
else console.log("a great date")

By removing spaces you detect values like "hello 2" that are taken as a date.
For the dates that contain strings like day name or month name ... I believe it is about string validation.

风流物 2024-12-12 03:08:29

这很简单:

// add you expresion
(/\d+-\d+-\d+/).test("2023-01-17 14:05:56.83419") // true

(/\d+-\d+-\d+/).test("202x-01-17 14:05:56.83419") // false

it is Simple:

// add you expresion
(/\d+-\d+-\d+/).test("2023-01-17 14:05:56.83419") // true

(/\d+-\d+-\d+/).test("202x-01-17 14:05:56.83419") // false
青瓷清茶倾城歌 2024-12-12 03:08:29

您可以使用此正则表达式,如果您想包含 2026..29,请更改 [1-5]:

^([1-2][1-9]|3[01])[\/\.-]((0[1-9])|1[0-2])[\/\.-](1\d{3}|20(([01]\d)|2[1-5]))$

You can use this regex, change [1-5] if you want to include 2026..29:

^([1-2][1-9]|3[01])[\/\.-]((0[1-9])|1[0-2])[\/\.-](1\d{3}|20(([01]\d)|2[1-5]))$
原来是傀儡 2024-12-12 03:08:29

此函数验证 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;
}

This function verifies that the input string in the format m/d/yyyy or mm/dd/yyyy can be converted to a date and that the date is a valid date matching the input string. Add more conditional checks to verify additional formats.

/**
 * 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;
}
倒数 2024-12-12 03:08:29

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

它涵盖以下情况:

  1. 捕获导致“无效日期”日期构造函数结果的任何输入;
  2. 捕获从技术角度来看日期“有效”,但从业务逻辑角度来看无效的情况,例如
  • new Date(null).getTime(): 0
  • new Date(true).getTime(): 1
  • new Date(-3.14).getTime(): -3
  • new Date(["1", "2"] ).toDateString(): 2001 年 1 月 2 日星期二
  • new Date([1, 2]).toDateString():2001 年 1 月 2 日星期二
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'

Here is what one could use to validate that the input is a number or a string that can be converted to a date object.

It covers the following cases:

  1. catching whatever input leads to "Invalid Date" date constructor result;
  2. catching the cases where the date is "valid" from technical point of view, but it is not valid from business logic point of view, like
  • 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'
橘香 2024-12-12 03:08:29

这就是我最终这样做的方式。这不会涵盖所有格式。
你必须做出相应的调整。我可以控制格式,所以它对我有用

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;
            }
        }

This is how I end up doing it. This will not cover all formats.
You have to adjust accordingly. I have control on the format, so it works for me

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;
            }
        }
╭ゆ眷念 2024-12-12 03:08:28

2015 更新

这是一个老问题,但其他新问题如:

作为此字符串的重复项而关闭,因此我认为在此处添加一些新信息很重要。我写它是因为我害怕想到人们实际上复制并粘贴了此处发布的一些代码并在生产中使用它。

这里的大多数答案要么使用一些复杂的正则表达式,这些表达式仅匹配一些非常特定的格式,并且实际上做得不正确(例如匹配 1 月 32 日,但不匹配广告中的实际 ISO 日期 - 请参阅 演示或者他们尝试将任何东西传递给Date 构造函数并祝愿一切顺利。

使用 Moment

正如我在 这个答案 目前有一个库可用于此:
Moment.js

这是一个在 JavaScript 中解析、验证、操作和显示日期的库,具有更丰富的 API比标准 JavaScript 日期处理函数。

它经过压缩/压缩后只有 12kB,可以在 Node.js 和其他地方使用:

bower install moment --save # bower
npm install moment --save   # npm
Install-Package Moment.js   # NuGet
spm install moment --save   # spm
meteor add momentjs:moment  # meteor

使用 Moment,您可以非常具体地检查有效日期。有时添加一些有关您期望的格式的线索非常重要。例如,诸如 06/22/2015 之类的日期看起来像是有效日期,除非您使用格式 DD/MM/YYYY,在这种情况下,该日期应被视为无效而被拒绝。有几种方法可以告诉 Moment 您期望的格式,例如:

moment("06/22/2015", "MM/DD/YYYY", true).isValid(); // true
moment("06/22/2015", "DD/MM/YYYY", true).isValid(); // false

true 参数存在,因此 Moment 不会尝试解析输入(如果不存在)不完全符合提供的格式之一(我认为这应该是默认行为)。

您可以使用内部提供的格式:

moment("2015-06-22T13:17:21+0000", moment.ISO_8601, true).isValid(); // true

并且可以使用多种格式作为数组:

var formats = [
    moment.ISO_8601,
    "MM/DD/YYYY  :)  HH*mm*ss"
];
moment("2015-06-22T13:17:21+0000", formats, true).isValid(); // true
moment("06/22/2015  :)  13*17*21", formats, true).isValid(); // true
moment("06/22/2015  :(  13*17*21", formats, true).isValid(); // false

请参阅:演示

其他库

如果您不想使用 Moment.js,还有其他库:

2016 更新

我创建了 immoment 模块类似于 Moment(的子集),但不会因现有对象的突变而导致意外(请参阅 文档 了解更多信息)。

2018

今天更新我建议使用 Luxon 进行日期/时间操作,而不是 Moment,这(与 Moment 不同)使所有对象不可变,因此不会出现与日期隐式突变相关的令人讨厌的意外情况。

更多信息

另请参阅:

A Rob Gravelle 关于 JavaScript 日期解析库的系列文章:

底线

当然,任何人都可以尝试重新发明轮子,编写正则表达式(但是实际阅读 ISO 8601 和 RFC第 3339 章平台?在所有地区?将来?)或者您可以使用经过测试的解决方案并利用时间来改进它,而不是重新发明它。此处列出的所有库都是开源、免费软件。

2015 Update

It is an old question but other new questions like:

get closed as duplicates of this one, so I think it's important to add some fresh info here. I'm writing it because I got scared thinking that people actually copy and paste some of the code posted here and use it in production.

Most of the answers here either use some complex regular expressions that match only some very specific formats and actually do it incorrectly (like matching January 32nd while not matching actual ISO date as advertised - see demo) or they try to pass anything to the Date constructor and wish for the best.

Using Moment

As I explained in this answer there is currently a library available for that:
Moment.js

It is a library to parse, validate, manipulate, and display dates in JavaScript, that has a much richer API than the standard JavaScript date handling functions.

It is 12kB minified/gzipped and works in Node.js and other places:

bower install moment --save # bower
npm install moment --save   # npm
Install-Package Moment.js   # NuGet
spm install moment --save   # spm
meteor add momentjs:moment  # meteor

Using Moment you can be very specific about checking valid dates. Sometimes it is very important to add some clues about the format that you expect. For example, a date such as 06/22/2015 looks like a valid date, unless you use a format DD/MM/YYYY in which case this date should be rejected as invalid. There are few ways how you can tell Moment what format you expect, for example:

moment("06/22/2015", "MM/DD/YYYY", true).isValid(); // true
moment("06/22/2015", "DD/MM/YYYY", true).isValid(); // false

The true argument is there so the Moment won't try to parse the input if it doesn't exactly conform to one of the formats provided (it should be a default behavior in my opinion).

You can use an internally provided format:

moment("2015-06-22T13:17:21+0000", moment.ISO_8601, true).isValid(); // true

And you can use multiple formats as an array:

var formats = [
    moment.ISO_8601,
    "MM/DD/YYYY  :)  HH*mm*ss"
];
moment("2015-06-22T13:17:21+0000", formats, true).isValid(); // true
moment("06/22/2015  :)  13*17*21", formats, true).isValid(); // true
moment("06/22/2015  :(  13*17*21", formats, true).isValid(); // false

See: DEMO.

Other libraries

If you don't want to use Moment.js, there are also other libraries:

2016 Update

I created the immoment module that is like (a subset of) Moment but without surprises caused by mutation of existing objects (see the docs for more info).

2018 Update

Today I recommend using Luxon for date/time manipulation instead of Moment, which (unlike Moment) makes all object immutable so there are no nasty surprises related to implicit mutation of dates.

More info

See also:

A series of articles by Rob Gravelle on JavaScript date parsing libraries:

Bottom line

Of course anyone can try to reinvent the wheel, write a regular expression (but please actually read ISO 8601 and RFC 3339 before you do it) or call buit-in constructors with random data to parse error messages like 'Invalid Date' (Are you sure this message is exactly the same on all platforms? In all locales? In the future?) or you can use a tested solution and use your time to improve it, not reinvent it. All of the libraries listed here are open source, free software.

只是在用心讲痛 2024-12-12 03:08:28

这就是我在我现在正在开发的应用程序中解决此问题的方法:

根据 krillgar 的反馈进行更新:

var isDate = function(date) {
    return (new Date(date) !== "Invalid Date") && !isNaN(new Date(date));
}

This is how I solved this problem in an app I'm working on right now:

updated based on feedback from krillgar:

var isDate = function(date) {
    return (new Date(date) !== "Invalid Date") && !isNaN(new Date(date));
}
怎樣才叫好 2024-12-12 03:08:28

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)

Would Date.parse() suffice?

See its relative MDN Documentation page.

Date.parse returns a timestamp if string date is valid. Here are some use cases:

// /!\ 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)
北风几吹夏 2024-12-12 03:08:28

new Date(date) === 'Invalid Date' 仅适用于 Firefox 和 Chrome。 IE8(我在我的机器上用于测试目的的那个)给出了 NaN。

正如已接受的答案所述,Date.parse(date) 也适用于数字。因此,为了解决这个问题,您还可以检查它是否不是一个数字(如果您想确认这一点)。

var parsedDate = Date.parse(date);

// You want to check again for !isNaN(parsedDate) here because Dates can be converted
// to numbers, but a failed Date parse will not.
if (isNaN(date) && !isNaN(parsedDate)) {
    /* do your work */
}

new Date(date) === 'Invalid Date' only works in Firefox and Chrome. IE8 (the one I have on my machine for testing purposes) gives NaN.

As was stated to the accepted answer, Date.parse(date) will also work for numbers. So to get around that, you could also check that it is not a number (if that's something you want to confirm).

var parsedDate = Date.parse(date);

// You want to check again for !isNaN(parsedDate) here because Dates can be converted
// to numbers, but a failed Date parse will not.
if (isNaN(date) && !isNaN(parsedDate)) {
    /* do your work */
}
_失温 2024-12-12 03:08:28

工作不一致,请注意!

isDate('Leyweg 1') 在 Chrome 上返回 true(Firefox 返回 false)

Does not work consistently, watch out!

isDate('Leyweg 1') returns true on Chrome (Firefox returns false) ????

Read: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse (Date.parse is called under the hood when invoking like so: new Date(someDateString).


Original answer:

function isDate(dateStr) {
  return !isNaN(new Date(dateStr).getDate());
}
  • This will work on any browser since it does not rely on "Invalid Date" check.
  • This will work with legacy code before ES6.
  • This will work without any library.
  • This will work regardless of any date format.
  • This does not rely on Date.parse which fails the purpose when values like "Spiderman 22" are in date string.
  • This does not ask us to write any RegEx.
习惯成性 2024-12-12 03:08:28

这里的答案都没有解决检查日期是否无效(例如 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];
} 

None of the answers here address checking whether the date is invalid such as February 31. This function addresses that by checking if the returned month is equivalent to the original month and making sure a valid year was presented.

//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];
} 
云巢 2024-12-12 03:08:28

像这样的事情怎么样?它将测试它是 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 进行更多的工作应该会很好。

How about something like this? It will test if it is a Date object or a date string:

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);
}

I should mention that this doesn't test for ISO formatted strings but with a little more work to the RegExp you should be good.

撩人痒 2024-12-12 03:08:28

使用正则表达式来验证它。

isDate('2018-08-01T18:30:00.000Z');

isDate(_date){
        const _regExp  = new RegExp('^(-?(?:[1-9][0-9]*)?[0-9]{4})-(1[0-2]|0[1-9])-(3[01]|0[1-9]|[12][0-9])T(2[0-3]|[01][0-9]):([0-5][0-9]):([0-5][0-9])(.[0-9]+)?(Z)?
);
        return _regExp.test(_date);
    }

Use Regular expression to validate it.

isDate('2018-08-01T18:30:00.000Z');

isDate(_date){
        const _regExp  = new RegExp('^(-?(?:[1-9][0-9]*)?[0-9]{4})-(1[0-2]|0[1-9])-(3[01]|0[1-9]|[12][0-9])T(2[0-3]|[01][0-9]):([0-5][0-9]):([0-5][0-9])(.[0-9]+)?(Z)?
);
        return _regExp.test(_date);
    }
回忆躺在深渊里 2024-12-12 03:08:28

通过参考以上所有评论,我得出了一个解决方案。

如果传递的 Date 是 ISO 格式或需要操作其他格式,则此方法有效。

var isISO = "2018-08-01T18:30:00.000Z";

if (new Date(isISO) !== "Invalid Date" && !isNaN(new Date(isISO))) {
    if(isISO == new Date(isISO).toISOString()) {
        console.log("Valid date");
    } else {
        console.log("Invalid date");
    }
} else {
    console.log("Invalid date");
}

您可以在此处在 JSFiddle 上玩。

By referring to all of the above comments, I have come to a solution.

This works if the Date passed is in ISO format or need to manipulate for other formats.

var isISO = "2018-08-01T18:30:00.000Z";

if (new Date(isISO) !== "Invalid Date" && !isNaN(new Date(isISO))) {
    if(isISO == new Date(isISO).toISOString()) {
        console.log("Valid date");
    } else {
        console.log("Invalid date");
    }
} else {
    console.log("Invalid date");
}

You can play here on JSFiddle.

一身软味 2024-12-12 03:08:28

这是一个仅使用 Date.parse() 的改进函数:

function isDate(dateToTest) {
    return isNaN(dateToTest) && !isNaN(Date.parse(dateToTest));
}

注意: Date.parse() 将解析数字:例如 Date.parse(1) 将返回一个日期。因此,我们在这里检查 dateToTest 是否不是数字,然后检查它是否是日期。

Here is an improved function that uses only Date.parse():

function isDate(dateToTest) {
    return isNaN(dateToTest) && !isNaN(Date.parse(dateToTest));
}

Note: Date.parse() will parse numbers: for example Date.parse(1) will return a date. So here we check if dateToTest is not a number then if it is a date.

回忆追雨的时光 2024-12-12 03:08:28

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

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

这是删除数字的行。因此,整个函数可能如下所示:

function isDate(sDate) {  
  if(sDate.toString() == parseInt(sDate).toString()) return false; 
  var tryDate = new Date(sDate);
  return (tryDate && tryDate.toString() != "NaN" && tryDate != "Invalid Date");  
}

console.log("100", isDate(100));
console.log("234", isDate("234"));
console.log("hello", isDate("hello"));
console.log("25 Feb 2018", isDate("25 Feb 2018"));
console.log("2009-11-10T07:00:00+0000", isDate("2009-11-10T07:00:00+0000"));

I know it's an old question but I faced the same problem and saw that none of the answers worked properly - specifically weeding out numbers (1,200,345,etc..) from dates, which is the original question. Here is a rather unorthodox method I could think of and it seems to work. Please point out if there are cases where it will fail.

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

This is the line to weed out numbers. Thus, the entire function could look like:

function isDate(sDate) {  
  if(sDate.toString() == parseInt(sDate).toString()) return false; 
  var tryDate = new Date(sDate);
  return (tryDate && tryDate.toString() != "NaN" && tryDate != "Invalid Date");  
}

console.log("100", isDate(100));
console.log("234", isDate("234"));
console.log("hello", isDate("hello"));
console.log("25 Feb 2018", isDate("25 Feb 2018"));
console.log("2009-11-10T07:00:00+0000", isDate("2009-11-10T07:00:00+0000"));

久随 2024-12-12 03:08:28

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

new Date('3000')

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

为了解决这个问题,我们可以使用strict中Day.js库的解析方法模式通过传递第三个 争论。它记录在他们的 String + Format 页面中。为了根据格式进行解析,我们还必须启用 CustomParseFormat 插件。我假设您可以在此处使用 ESM 导入或设置像 Webpack 这样的编译器

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

dayjs.extend(formatParser)

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

> false

I feel none of the answers correctly understood what the OP asked. The issue here is that JavaScript can parse any number as a valid date, since the Date object can parse a string like '3000' as the year and will return a valid Date instance:

new Date('3000')

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

To solve this, we can use the Day.js library's parsing method in strict mode by passing in a third argument. It's documented in their String + Format page. In order for parsing to work based on a format, we must also enable the CustomParseFormat plugin. I'm assuming you can use ESM imports here or have a compiler like Webpack set up

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

dayjs.extend(formatParser)

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

> false
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文