Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert ISO8601 date to epoch format (unix timestamp)

How do I convert ISO 8601 date (ex. 20140107) to Unix timestamp (ex. 1389120125) using javascript?

like image 631
Steve Avatar asked Jan 07 '14 18:01

Steve


1 Answers

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

like image 143
fvu Avatar answered Sep 21 '22 21:09

fvu