Andres Elizondo
Andres Elizondo

Reputation: 341

JavaScript new Date(string) compatible for most browsers (Dec 2016)

I've been dealing with this annoying bug when creating a new Date(string) in JavaScript. My question is, has anyone found a better/more standardized solution for this issue that works on most browsers? For example I've found that IE9 doesn't like .sss (miliseconds), then Firefox doesn't work correctly with the european date format (DD-MM-YYYY).

Let me know what you think!

Upvotes: 1

Views: 2003

Answers (2)

Andres Elizondo
Andres Elizondo

Reputation: 341

I have found the string format that works for most browsers is the following.

stringFormat = moment(dateObject).format("YYYY-MM-DDTHH:mm:ss");
date = new Date(stringFormat);

I use moment.js to provide even further compatibility, so far this works well for IE9+, Chrome and Firefox. But took me many several forums and other responses in SOF to find a good solution.

The biggest issue is being compatible with older browsers, locale formats, etc. For example this one was almost correct, but the I found that IE9 doesn't like .sss (miliseconds) and wasn't working either. Firefox had errors with european Date formats too.

Does anyone have a better way to deal with this? Please share the knowledge! :)

Upvotes: 1

salezica
salezica

Reputation: 76909

According to MDN:

Note: parsing of date strings with the Date constructor (and Date.parse, they are equivalent) is strongly discouraged due to browser differences and inconsistencies. Support for RFC 2822 format strings is by convention only. Support for ISO 8601 formats differs in that date-only strings (e.g. "1970-01-01") are treated as UTC, not local.

The same applies to Date.parse(). If you fear such inconsistencies (because your browser support is very extensive, or because you handle data from external sources), you can always use the full constructor:

new Date(year, month, [day, hour, minute, second, millisecond])

The parameters between brackets are optional. If you can parse the date using a reliable tool (such as moment.js, as you mentioned), you can then build a native Date with no danger using this.

It's cumbersome, but pack it into a function and never look at it again.

Upvotes: 2

Related Questions