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.
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.
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.
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.
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));
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With