1

This works in Chrome but not in Firefox.

new Date("2013-06-03 17:09:06-0400")
  • Works fine in Chrome
  • Gives 'NaN' in Firefox.

I would appreciate any help.

MickJ
  • 2,127
  • 3
  • 20
  • 34
  • Related / similar question with solution (no real answer): http://stackoverflow.com/questions/3566125/problem-with-date-formats-in-javascript-with-different-browsers – Tessmore Jun 11 '13 at 18:25
  • The accepted answer in that question does not work for my case. I tried using: new Date('2013-06-03 17:09:06-0400'.replace(/\-/g,'\/').replace(/[T|Z]/g,' ')) but it gave 'Invalid date'. – MickJ Jun 11 '13 at 18:28
  • No worries. Answer from @benastan worked perfectly for me. – MickJ Jun 11 '13 at 18:34
  • 1
    Take a look at [moment.js](http://momentjs.com) for better parsing support. – Matt Johnson-Pint Jun 12 '13 at 03:12
  • I did. It looks great. Thanks for the suggestion. Especially since I was trying to use it for a very similar purpose. – MickJ Jun 12 '13 at 20:15

2 Answers2

2

Take a look at Mozilla Developer Network's Date and Date.parse documentation.

Specifically, it states:

Alternatively, the date/time string may be in ISO 8601 format. Starting with JavaScript 1.8.5 (Firefox 4), a subset of ISO 8601 is supported. For example, "2011-10-10" (just date) or "2011-10-10T14:48:00" (date and time) can be passed and parsed.

If you throw a 'T' in between the date and the time you get:

new Date("2013-06-03T17:09:06-0400")
=> Mon Jun 03 2013 14:09:06 GMT-0700 (PDT)

In both Chrome and Mozilla, although you have to account for the the current timezone (thus PDT) of the user's system.

benastan
  • 2,268
  • 15
  • 14
  • Awesome. Adding the 'T' does the magic. Works in both Firefox and Chrome now. Many Thanks. – MickJ Jun 11 '13 at 18:30
0

In my experience, the only reliable way to construct a date object from a string in JavaScript is to parse the string yourself, and then use the version of the constructor that takes a separate numeric parameter for each field.

The string-based constructor is far too prone to issues with locale-related parsing errors.

Alnitak
  • 334,560
  • 70
  • 407
  • 495