0
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 GMT-0800 (PST)

What can I do to make Safari oblige to January 1st? I do not want to use moment.js or another framework to resolve this. If you are a JavaScript Date() object master, please point me in the right direction.

Thank you.

markreyes
  • 1,249
  • 1
  • 13
  • 27

1 Answers1

2

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 = new Date(arr[0], arr[1]-1, arr[2], arr[3], arr[4], arr[5]);

In one function:

function parseDateString(dateString) {
    var arr = dateString.split(/\D/);
    return new Date(arr[0], arr[1]-1, arr[2], arr[3], arr[4], arr[5]);
}

I hope this answers your question.

NocNit
  • 280
  • 1
  • 7