Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
422 views
in Technique[技术] by (71.8m points)

javascript - 检查字符串是否为日期值(Check if a string is a date value)

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.

(例如我具有值10-11-200910/11/20092009-11-10T07:00:00+0000应该所有被识别为日期值,并且这些值20010350 ,其不应被识别为日期值。)

What is the simplest way to check this, if this is even possible?

(如果可能的话,最简单的检查方法是什么?)

Because timestamps would also be allowed.

(因为时间戳也将被允许。)

  ask by Thys translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 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.

(此处的大多数答案要么使用一些仅匹配某些非常特定格式的复杂正则表达式,然后实际执行不正确(例如匹配1月32日,而不匹配所宣传的实际ISO日期-参见demo ), 要么尝试将任何内容传递给Date构造函数并祝一切顺利。)

Using Moment(使用时刻)

As I explained in this answer there 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,可在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.

(使用Moment,您可以非常明确地检查有效日期。)

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.

(例如,除非您使用DD / MM / YYYY格式,否则日期(例如06/22/2015)看起来像是有效日期,在这种情况下,该日期应被视为无效。)

There are few ways how you can tell Moment what format you expect, for example:

(有几种方法可以告诉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 exactly conform to one of the formats provided (it should be a default behavior in my opinion).

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

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 .

(参见: 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 immoment module that is like (a subset of) Moment but without surprises caused by mutation of existing objects (see the docs for more info).

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

2018 Update(2018更新)

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.

(今天,我建议使用Luxon代替Moment来进行日期/时间操作(与Moment不同),Moment使所有对象不可变,因此不会出现与隐式更改日期有关的令人讨厌的惊喜。)

More info(更多信息)

See also:

(也可以看看:)

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

(Rob Gravelle撰写的有关JavaScript日期解析库的系列文章:)

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.

(当然,任何人都可以尝试重新发明轮子,编写正则表达式(但是在执行此操作之前, 请先阅读ISO 8601和RFC 3339)或使用随机数据调用buit-in构造函数以解析诸如'Invalid Date''Invalid Date'错误消息(确定此消息在所有平台上都完全相同 ?在所有语言环境中?将来?), 或者您可以使用经过测试的解决方案并花费时间改进它,


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...