How to determine if a string is a date format?

I have several lines: 2012-02-05T07:42:47.000Z mixed with other lines. It is always in this format. (but the numbers do not match, of course ... times are different) (not Sun, 05 Feb 2012 07:42:47 GMT )

I want to know if a string matches this format. How can I determine this? It is so complicated with colons, periods, etc.

0
javascript string date regex datetime
source share
6 answers

Regex [0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}\.[0-9]{3}Z

+2
source share

Those for which !isNaN(+new Date(s)) ?

0
source share

Try matching with the following regular expression:

 var pattern = /\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}.\d{3}Z/; var d = "2012-02-05T07:42:47.000Z"; if(d.match(pattern) !== null){ //success } else { //failed } 
0
source share

You can use Date.parse (your_string) and check the result. This will check for any valid date format, as opposed to regex. http://www.w3schools.com/jsref/jsref_parse.asp

I just realized that your line is always in the given format, but unlike the regular expression, that the function checks the correctness of the day / month / year, etc. Therefore, it is possible to carry 2 checks: 1st to check the format of the string, 2nd to check the correctness of the numbers.

0
source share

Replace all numbers with the # sign so that "2012-02-05T07: 42: 47.000Z" looks like this: #### - ## - ## T ##: ##: ##. ### Z ", then you can do a direct search for strings.

I used this technique to search for social security numbers in a large block of document text, I converted all numbers to # characters, I just needed to look for lines that were ### - ## - ####

0
source share

For what it's worth, you can use moment.js for this.

 var check1 = "2012-02-05T07:42:47.000Z"; alert(moment(check1)); //Sat Feb 04 2012 23:42:47 GMT-0800 var check2 = "201-02-05T07:42:47.000Z"; alert(moment(check2)); //Invalid date 

Play here: http://jsfiddle.net/remus/KFjZF/

0
source share

All Articles