-2

I'm trying to convert a string into a Date object and it looks like there is a lot of cross browser compatibility issue around this.

My string is simple "2016-1-11 10:30". Code is also simple

var d = new Date(str);

Firefox and Chrome are both happy this format but Safari refuse to turn it into an valid object.

Is there a way or a javascript library that iron this out?

lang2
  • 11,433
  • 18
  • 83
  • 133
  • 5
    Library requests are offtopic for SO, but the usual goto library for this sort of stuff is [momentjs](http://momentjs.com/). As for your underlying issue - yes, what you're passing in is "non-standard" as far as the spec is concerned, so implementations are free to interpret it (or not) how they choose. – James Thorpe Jan 12 '16 at 14:29
  • Possible duplicate of [Where can I find documentation on formatting a date in JavaScript?](http://stackoverflow.com/questions/1056728/where-can-i-find-documentation-on-formatting-a-date-in-javascript) – JJJ Jan 12 '16 at 14:37
  • What's about this `2016-01-11 10:30:00`? – Lewis Jan 12 '16 at 14:38
  • 1
    @Tresdin That's an improvement, but it doesn't strictly match [the standard](http://www.ecma-international.org/ecma-262/5.1/#sec-15.9.1.15) (there's no `T`), so browsers could still technically do what they like. – James Thorpe Jan 12 '16 at 14:39
  • @JamesThorpe Ahha, that's a MySQL one. Thanks for the hint. It should be `2016-01-11T03:30:00.000Z`. That's why I prefer storing datetime in number `1452483000000`. – Lewis Jan 12 '16 at 14:57

2 Answers2

-2

Safari hates using hyphens for date delimiters.

Try the following code to replace them with slashes

var d = new Date(str.replace(/-/g, "/")));

it will replace all occurrences of - with a forward slash and reformat your date to: 2016/1/11 10:30. This should keep Safari sufficiently happy but may have other implications on your code if you rely on the hyphen format.

William Cross
  • 347
  • 1
  • 9
-2

As @James Thorpe said moment.js is the way to go. If you cant by any chance include moment.js then the standard format here should be YYYY-MM-DDTHH:mm:ssZ

Chrome and Firefox will forgive you for that but all browsers wont.

Aukhan
  • 481
  • 4
  • 9