Determine if the string format is "May 16, 2013" or UNIX timestamp with Javascript

Execution of some data related to a large data set. The data has a "date" field that randomly switches between the format, for example, "1370039735000" and "May 16, 2013." So far, I have converted other date fields using

new Date("May 16, 2013") 

or

 new Date(NumberLong(1370039735000)) 

How can I tell the difference between the two using regex or some other ways? I use MongoDB, but all Javascript.

+6
source share
3 answers

If it is a unix timestamp, it is only numbers, and if not, then the actual string (not empty or logical), and javascript has a function for it, isNaN

 isNaN(datestring_or_number) 

can be used easily

 new Date(isNaN(str) ? str : NumberLong(str)); 
+5
source

From your post, I assume that you are absolutely 100% sure that these are the only two possible formats. If this is not the case, then comment / edit the post.

Testing, if the date contains a letter, should consist in concluding a transaction in a simple way.

 /[az]/i.test("May 16, 2013") // true, the date is written out /[az]/i.test(1370039735000) // false, it unix epoch format 
+2
source

If you are worried about speed, you should just test the Regex “^ \ D” (not the number), because as soon as it hits the “M” in the “May ...”, it will fail. This will work quickly and run a minimum number of times. You can also consider getting the substring of the first character in the string and try to convert it to int, and if it fails, then this is true. However, keeping a regular expression like this, speed should not be a problem.

+1
source

All Articles