检查字符串是否为日期值
检查值是否为有效日期的简单方法是什么,允许任何已知的日期格式。
例如,我有值 10-11-2009
、10/11/2009
、2009-11-10T07:00:00+0000
这些值都应该被识别为日期值,而值 200
、10
、350
则不应被识别为日期值。如果可能的话,检查这一点的最简单方法是什么?因为时间戳也是允许的。
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(25)
我会
在这里播放
I would do this
Play here
这个可调用函数工作完美,对于有效日期返回 true。
请务必使用 ISO 格式的日期(yyyy-mm-dd 或 yyyy/mm/dd)进行调用:
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):
检查对象是否可以使用与日期相关的函数来确定它是否是日期对象是否可以?
喜欢
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
我发现这个解决方案非常好:
您可以轻松添加更多格式
i find this solution very good:
and you can easily add more formats
这是一个极简主义版本。
Here's a minimalist version.
好吧,这是一个老问题,但我在检查此处的解决方案时找到了另一个解决方案。对我来说,检查函数 getTime() 是否存在于日期对象中:
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:
我认为最直接的解决方案是
如果它不是有效日期,它将是 NaN,即不大于 0。
I think the most straight forward solution would be
If it is not a valid date, it will be NaN, which is not greater than 0.
我相信这是仅包含数字的日期最简单的工作答案:
通过删除空格,您可以检测到诸如“hello 2”之类的值,这些值被视为日期。
对于包含日期名称或月份名称等字符串的日期......我相信这是关于字符串验证的。
I believe this is the simplest working answer for date that contains only numbers:
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.
这很简单:
it is Simple:
您可以使用此正则表达式,如果您想包含 2026..29,请更改 [1-5]:
You can use this regex, change [1-5] if you want to include 2026..29:
此函数验证 m/d/yyyy 或 mm/dd/yyyy 格式的输入字符串是否可以转换为日期,并且该日期是与输入字符串匹配的有效日期。添加更多条件检查以验证其他格式。
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.
下面是可以用来验证输入是否是可以转换为
日期对象
的数字
或字符串
的方法。它涵盖以下情况:
“无效日期”
日期构造函数
结果的任何输入;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 日星期二
Here is what one could use to validate that the input is a
number
or astring
that can be converted to adate object
.It covers the following cases:
"Invalid Date"
date constructor
result;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
这就是我最终这样做的方式。这不会涵盖所有格式。
你必须做出相应的调整。我可以控制格式,所以它对我有用
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
2015 更新
这是一个老问题,但其他新问题如:
作为此字符串的重复项而关闭,因此我认为在此处添加一些新信息很重要。我写它是因为我害怕想到人们实际上复制并粘贴了此处发布的一些代码并在生产中使用它。
这里的大多数答案要么使用一些复杂的正则表达式,这些表达式仅匹配一些非常特定的格式,并且实际上做得不正确(例如匹配 1 月 32 日,但不匹配广告中的实际 ISO 日期 - 请参阅 演示)或者他们尝试将任何东西传递给
Date
构造函数并祝愿一切顺利。使用 Moment
正如我在 这个答案 目前有一个库可用于此:
Moment.js
这是一个在 JavaScript 中解析、验证、操作和显示日期的库,具有更丰富的 API比标准 JavaScript 日期处理函数。
它经过压缩/压缩后只有 12kB,可以在 Node.js 和其他地方使用:
使用 Moment,您可以非常具体地检查有效日期。有时添加一些有关您期望的格式的线索非常重要。例如,诸如 06/22/2015 之类的日期看起来像是有效日期,除非您使用格式 DD/MM/YYYY,在这种情况下,该日期应被视为无效而被拒绝。有几种方法可以告诉 Moment 您期望的格式,例如:
true
参数存在,因此 Moment 不会尝试解析输入(如果不存在)不完全符合提供的格式之一(我认为这应该是默认行为)。您可以使用内部提供的格式:
并且可以使用多种格式作为数组:
请参阅:演示。
其他库
如果您不想使用 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:
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:
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:
And you can use multiple formats as an array:
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.这就是我在我现在正在开发的应用程序中解决此问题的方法:
根据 krillgar 的反馈进行更新:
This is how I solved this problem in an app I'm working on right now:
updated based on feedback from krillgar:
Date.parse()
就足够了吗?请参阅其相关的 MDN 文档页面。
如果字符串日期有效,
Date.parse
返回时间戳。以下是一些用例: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:new Date(date) === 'Invalid Date'
仅适用于 Firefox 和 Chrome。 IE8(我在我的机器上用于测试目的的那个)给出了 NaN。正如已接受的答案所述,
Date.parse(date)
也适用于数字。因此,为了解决这个问题,您还可以检查它是否不是一个数字(如果您想确认这一点)。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).工作不一致,请注意!
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:
这里的答案都没有解决检查日期是否无效(例如 2 月 31 日)的问题。此函数通过检查返回的月份是否等于原始月份并确保提供有效的年份来解决这个问题。
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.
像这样的事情怎么样?它将测试它是 Date 对象还是日期字符串:
我应该提到,这不会测试 ISO 格式的字符串,但对 RegExp 进行更多的工作应该会很好。
How about something like this? It will test if it is a Date object or a date string:
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.
使用正则表达式来验证它。
Use Regular expression to validate it.
通过参考以上所有评论,我得出了一个解决方案。
如果传递的
Date
是 ISO 格式或需要操作其他格式,则此方法有效。您可以在此处在 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.You can play here on JSFiddle.
这是一个仅使用
Date.parse()
的改进函数:注意: Date.parse() 将解析数字:例如
Date.parse(1)
将返回一个日期。因此,我们在这里检查dateToTest
是否不是数字,然后检查它是否是日期。Here is an improved function that uses only
Date.parse()
:Note: Date.parse() will parse numbers: for example
Date.parse(1)
will return a date. So here we check ifdateToTest
is not a number then if it is a date.我知道这是一个老问题,但我遇到了同样的问题,发现没有一个答案能正常工作——特别是从日期中剔除数字(1,200,345 等),这是最初的问题。这是我能想到的一个相当非正统的方法,它似乎有效。是否有失败的情况请指出。
这是删除数字的行。因此,整个函数可能如下所示:
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.
This is the line to weed out numbers. Thus, the entire function could look like:
我觉得没有一个答案正确理解了OP的要求。这里的问题是 JavaScript 可以将任何数字解析为有效日期,因为
Date
对象可以将'3000'
之类的字符串解析为年份,并返回有效的日期实例:为了解决这个问题,我们可以使用strict中Day.js库的解析方法模式通过传递第三个 争论。它记录在他们的 String + Format 页面中。为了根据格式进行解析,我们还必须启用
CustomParseFormat
插件。我假设您可以在此处使用 ESM 导入或设置像 Webpack 这样的编译器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: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