Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Doing some data wrangling with a large dataset. The data has a "date" field that randomly switches between a format like "1370039735000" and "May 16, 2013". So far I've converted other date fields with either

new Date("May 16, 2013")

or

new Date(NumberLong(1370039735000))

How can I tell the difference between the two using regex or some other means? I'm using MongoDB but it's all Javascript.

like image 469
Julian Avatar asked Dec 27 '13 19:12

Julian


People also ask

What is a Unix timestamp JavaScript?

The UNIX timestamp is defined as the number of seconds since January 1, 1970 UTC. In JavaScript, in order to get the current timestamp, you can use Date. now() . It's important to note that Date. now() will return the number of milliseconds since January, 1 1970 UTC.

What is Unix timestamp format?

Unix epoch timestamps are supported in the following formats: 10 digit epoch time format surrounded by brackets (or followed by a comma). The digits must be at the very start of the message. For example, [1234567890] or [1234567890, other] followed by the rest of the message.

What JavaScript data type is used to store a timestamp?

The Date object is a built-in object in JavaScript that stores the date and time. It provides a number of built-in methods for formatting and managing that data.


3 Answers

If it's a unix timestamp, it's numbers only, and if it's not, it's an actual string (not empty or boolean) and javascript has a function for that, isNaN

isNaN(datestring_or_number)

can be easily used

new Date(isNaN(str) ? str : NumberLong(str));
like image 114
adeneo Avatar answered Oct 19 '22 13:10

adeneo


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

Testing if the date contains a letter should seal the deal in a simple manner.

/[a-z]/i.test("May 16, 2013") // true, the date is written out
/[a-z]/i.test(1370039735000) // false, it's unix epoch format
like image 2
dee-see Avatar answered Oct 19 '22 13:10

dee-see


If you're worried about speed, you should just test against the Regex "^\D" (not a digit) because as soon as it hits the "M" in "May..." it will fail. This will fail quickly and only run the minimum amount of times. You might also consider just getting a substring of the first character in the string and trying to convert it to an int and if it fails, then the same thing is true. By keeping the Regex short like that however, speed shouldn't be an issue.

like image 1
Jon Upchurch Avatar answered Oct 19 '22 14:10

Jon Upchurch