Convert ISO8601 date to epoch format (unix timestamp)
If you're using a browser with ECMAscript 5 support, Date.parse() accepts an ISO-8601 datestring and returns an epoch value in milliseconds, so just divide that by 1000 and you're done.
However
Contrary to what you state, your input string doesn't conform to the ISO-8601 subset defined in ECMAscript because it's lacking the dashes between the individual fields. As far as I know, the dashes are mandatory for EMCAscript (even though ISO 8601 itself allows the dashless, or basic, format). So maybe you'll have to do some string parsing and use one of Date's constructors and its getTime() method to obtain the same
new Date(year, month [, day, hour, minute, second, millisecond]);
If you want to remain compatible with older browsers but still use Date.parse, you could consider including this shim
Steve
Updated on June 16, 2022Comments
-
Steve almost 2 years
How do I convert ISO 8601 date (ex. 20140107) to Unix timestamp (ex. 1389120125) using javascript?
-
Steve over 10 yearsThanks for your answer. I tried
Date.parse(20140107);
and gotNaN
. Any ideas why it is not working? -
fvu over 10 years@Steve that's exactly the issue I tried to explain in my answer, plus a bonus one: you have to pass that variable as a string, otherwise it will be seen as a number. However Javascript does not support the basic, dash-less representation of dates meaning that
Date.parse("2014-01-07")
will work whereasDate.parse("20140107")
won't. If you're stuck with the latter some string parsing will be required. -
Steve over 10 years@fvu thanks for the explanation. I appreciate it. :)