Skip to content Skip to sidebar Skip to footer

Utc Date In Date() Object Outputs Differently In Safari

var dateString = '2018-01-01T00:00:00'; new Date(dateString); Chrome, Edge and Firefox (right): Mon Jan 01 2018 00:00:00 GMT-0800 (PST) Safari (wrong): Sun Dec 31 2017 16:00:00 G

Solution 1:

Some browsers handle date strings differently. Mozilla notes this problem on their Date documentation page:

Parsing of date strings with the Date constructor (and Date.parse, they are equivalent) is strongly discouraged due to browser differences and inconsistencies. - Source

They also note this on their Date.parse() documentation page, which gives a hint as to the solution:

It is not recommended to use Date.parse as until ES5, parsing of strings was entirely implementation dependent. There are still many differences in how different hosts parse date strings, therefore date strings should be manually parsed (a library can help if many different formats are to be accommodated). - Source

As noted in this answer, you can best split up the string and use the separated Date() constructor. Example code:

var arr = "2018-01-01T00:00:00".split(/\D/);
var date = newDate(arr[0], arr[1]-1, arr[2], arr[3], arr[4], arr[5]);

In one function:

functionparseDateString(dateString) {
    var arr = dateString.split(/\D/);
    returnnewDate(arr[0], arr[1]-1, arr[2], arr[3], arr[4], arr[5]);
}

I hope this answers your question.

Post a Comment for "Utc Date In Date() Object Outputs Differently In Safari"