Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I parse this date string consistently across browsers?

I'm using Javascript's Date object to parse a string into a milliseconds timestamp. I'm using Date.parse(), and the strings I'm parsing are of the following format: "2012-07-06 12:59:36-0600"

Date.parse performs nicely in Chrome, parsing into the correct timestamp I'd anticipate. However, every other browser returns "NaN" when I run the string through Date.parse().

I know that the Date object implementation is browser-specific, but I'd like to find a javascript solution that's capable of parsing strings of this type for any browser. Any suggestions on what else I could use in Javascript to achieve this?

like image 636
dsw88 Avatar asked Jul 06 '12 19:07

dsw88


2 Answers

Convert the input to valid ISO 8601:

Date.parse("2012-07-06 12:59:36-0600".replace(' ', 'T'));

This was tested (and works) in Firefox.

Note:

Note that while time zone specifiers are used during date string parsing to properly interpret the argument, they do not affect the value returned, which is always the number of milliseconds between January 1, 1970 00:00:00 UTC and the point in time represented by the argument.

  • https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date/parse
like image 110
Wayne Avatar answered Sep 23 '22 17:09

Wayne


Have you tried DateJS? Maybe you don't want to add another library, but it will solve your crossbrowser problem.

like image 45
davidethell Avatar answered Sep 22 '22 17:09

davidethell