Saqib Ali
Saqib Ali

Reputation: 12545

How can I convert this string to a Javascript date in both Chrome and Firefox?

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?

Upvotes: 2

Views: 49

Answers (3)

omarjmh
omarjmh

Reputation: 13888

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.

Upvotes: 2

germanio
germanio

Reputation: 859

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.

Upvotes: 1

Valter Júnior
Valter Júnior

Reputation: 948

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()

Upvotes: 1

Related Questions