2

I have a string in Javascript: '2008-03-09 18:02:29 UTC' I want to convert it into a date object. So I do the following:

> new Date('2008-03-09 18:02:29 UTC')

This works fine in Google Chrome (Version 49.0.2623.87, 64-bit):

> new Date('2008-03-09 18:02:29 UTC');
Sun Mar 09 2008 14:02:29 GMT-0400 (EDT)

But when I do the same think in Firefox (Version 45.0.1), it fails:

> new Date('2008-03-09 18:02:29 UTC');
Invalid Date

Is there some code that I can write that will do this conversion properly in both browsers?

Saqib Ali
  • 11,931
  • 41
  • 133
  • 272

3 Answers3

2

Using hyphens (-) instead of slashes (/) works in WebKit browsers, but not in IE or FF. Beware the UTC parse of YYYY-MM-DD!

http://dygraphs.com/date-formats.html

Edit: As the other answers have mentioned, moment is a great lib for this sort of stuff.

omarjmh
  • 13,632
  • 6
  • 34
  • 42
1

Have you ever heard about moment.js? Please see Moment.js

You can solve this problem like this:

moment('2008-03-09 18:02:29 UTC')

And if you want Date object you can use this:

moment('2008-03-09 18:02:29 UTC').toDate()
Valter Júnior
  • 948
  • 7
  • 19
1

If you can add a library to your UI, try using moment.js (http://momentjs.com/docs/#/parsing/special-formats/).

You can specify even a custom format.

UPDATE:

Try this:

moment.utc("2008-03-09 18:02:29 UTC", "YYYY-MM-DD HH:mm:ss");

I have tried it both in Chrome and Firefox and it works beautifully. Remember, if you are not using .utc(), the time gets your timezone, not UTC.

germanio
  • 861
  • 1
  • 17
  • 27
  • to the downvoters, at least explain why, doesn't this answer provides a solution to the question? – germanio Mar 30 '16 at 18:52
  • 1
    I downvoted because mentioning a library should be a comment, futher more the exact question is: Is there some code that I can write that will do this conversion properly in both browsers? please read the following: http://stackoverflow.com/help/how-to-answer I will upvote the hell out of your answer if you give him the code! – omarjmh Mar 30 '16 at 18:55
  • fair enough, there you have an improved answer – germanio Mar 30 '16 at 19:10
  • 1
    Sorry, not trying to be a stickler, I got slammed for this when I was answering my first few too, I upvoted now, thanks! – omarjmh Mar 30 '16 at 19:11