Javascript 检查字符串是否为日期值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7445328/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Check if a string is a date value
提问by Thizzer
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.
例如,我有值10-11-2009
, 10/11/2009
,2009-11-10T07:00:00+0000
它们都应该被识别为日期值,而值200
, 10
,350
不应该被识别为日期值。如果这可能的话,最简单的检查方法是什么?因为时间戳也是允许的。
采纳答案by Asmor
回答by rsp
2015 Update
2015年更新
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 eitheruse 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) orthey try to pass anything to the Date
constructor and wish for the best.
这里的大多数答案要么使用一些复杂的正则表达式,这些表达式只匹配一些非常特定的格式,但实际上做错了(比如匹配 1 月 32 日,而不匹配所宣传的实际 ISO 日期 - 请参阅演示),或者他们尝试将任何内容传递给Date
构造函数和祝最好。
Using Moment
使用时刻
As I explained in this answerthere is currently a library available for that: Moment.js
正如我在这个答案中所解释的,目前有一个可用的库: 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.
它是一个在 JavaScript 中解析、验证、操作和显示日期的库,它具有比标准 JavaScript 日期处理函数更丰富的 API。
It is 12kB minified/gzipped and works in Node.js and other places:
它是 12kB 压缩/gzipped 并在 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
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 之类的日期看起来像是一个有效日期,除非您使用 DD/MM/YYYY 格式,在这种情况下,应将该日期视为无效日期而拒绝。有几种方法可以告诉 Moment 您期望的格式,例如:
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 exactlyconform to one of the formats provided (it should be a default behavior in my opinion).
该true
参数是有那么瞬间将不尝试解析输入,如果它不正好符合所提供的格式之一(它应该是在我看来,一个默认的行为)。
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:
如果您不想使用 Moment.js,还有其他库:
2016 Update
2016年更新
I created the immomentmodule that is like (a subset of) Moment but without surprises caused by mutation of existing objects (see the docsfor more info).
我创建了immoment模块,它类似于 Moment(的一个子集),但没有由现有对象的突变引起的意外(有关更多信息,请参阅文档)。
2018 Update
2018 更新
Today I recommend using Luxonfor 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.
今天,我建议使用Luxon进行日期/时间操作,而不是 Moment,后者(与 Moment 不同)使所有对象不可变,因此不会出现与日期隐式突变相关的令人讨厌的意外。
More info
更多信息
See also:
也可以看看:
- Managing Dates and Times Using Moment.jsby Jay Raj
- Working with JavaScript Dates Using Moment.jsby Bradley Holbrook
- 使用 Moment.js 管理日期和时间by Jay Raj
- 使用 Moment.js 处理 JavaScript 日期by Bradley Holbrook
A series of articles by Rob Gravelle on JavaScript date parsing libraries:
Rob Gravelle 关于 JavaScript 日期解析库的一系列文章:
- A Roundup of Popular JavaScript Date Parsing Libraries: Moment.js
- A Roundup of Popular JavaScript Date Parsing Libraries: Datejs
- A Roundup of Popular JavaScript Date Parsing Libraries: XDate
Bottom line
底线
Of course anyone can try to reinvent the wheel, write a regular expression (but pleaseactually 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 sameon all platforms? In all locales? In the future?) oryou 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.
当然,任何人都可以尝试重新发明轮子,编写一个正则表达式(但请在开始之前实际阅读 ISO 8601 和 RFC 3339)或使用随机数据调用内置构造函数来解析错误消息,例如'Invalid Date'
(你确定这条消息是在所有平台上完全相同?在所有地区?在未来?)或者您可以使用经过测试的解决方案并花时间改进它,而不是重新发明它。这里列出的所有库都是开源的免费软件。
回答by Neil Girardi
This is how I solved this problem in an app I'm working on right now:
这就是我在我现在正在开发的应用程序中解决这个问题的方法:
updated based on feedback from krillgar:
根据 krillgar 的反馈更新:
var isDate = function(date) {
return (new Date(date) !== "Invalid Date") && !isNaN(new Date(date));
}
or...
或者...
var isDate = function(date) {
return (new Date(date) !== "Invalid Date" && !isNaN(new Date(date)) ) ? true : false;
}
....
....
回答by krillgar
new Date(date) === 'Invalid Date'
only works in Firefox and Chrome. IE8 (the one I have on my machine for testing purposes) gives NaN.
new Date(date) === 'Invalid Date'
仅适用于 Firefox 和 Chrome。IE8(我在我的机器上用于测试目的的那个)给出了 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).
正如接受的答案所述,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 */
}
回答by jwerre
How about something like this? It will test if it is a Date object or a date string:
这样的事情怎么样?它将测试它是 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);
}
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.
我应该提一下,这不会测试 ISO 格式的字符串,但对 RegExp 做更多的工作,你应该会很好。
回答by ykay says Reinstate Monica
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.
这里的答案都没有解决检查日期是否无效的问题,例如 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];
}
回答by Nikhil Zurunge
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.
如果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");
}
You can play hereon JSFiddle.
你可以在这里玩JSFiddle。
回答by lpradhap
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);
}
回答by A-Sharabiani
Here is an improved function that uses only Date.parse()
:
这是一个仅使用的改进函数Date.parse()
:
function isDate(s) {
if(isNaN(s) && !isNaN(Date.parse(s)))
return true;
else return false;
}
Note:Date.parse() will parse numbers: for example Date.parse(1)
will return a date. So here we check if s
is not a number the, if it is a date.
注意:Date.parse() 将解析数字:例如Date.parse(1)
将返回一个日期。所以在这里我们检查是否s
不是数字,如果是日期。