When I convert the date string 2019-02-16T10:00:00
into a JS Date object in timezone GMT+0100 (CET)
, and then call .toISOString()
I expect to get the ISO date/time 2019-12-01T09:10:10.000Z
(-1 hour).
However, what I am seeing is:
Safari (incorrect):
new Date('2019-12-01T10:10:10').toISOString()
\\ returns 2019-12-01T10:10:10.000Z
Chrome (correct):
new Date('2019-12-01T10:10:10').toISOString()
\\ returns 2019-12-01T09:10:10.000Z
FireFox (correct):
new Date('2019-12-01T10:10:10').toISOString()
\\ returns 2019-12-01T09:10:10.000Z
Am I missing something, or is this a known Safari issue?
It looks like Safari takes the provided input time as the time in UTC, but Chrome and Firefox are using the local time zones. I could not find any official document supporting this behaviour. But you can easily verify it from your browser. Here are outputs for me in India (GMT+530)
.
Chrome/FF:
new Date('2019-12-01T10:10:10Z').toISOString()
"2019-12-01T10:10:10.000Z"
new Date('2019-12-01T10:10:10').toISOString()
"2019-12-01T04:40:10.000Z"
Safari:
new Date('2019-12-01T10:10:10').toISOString()
"2019-12-01T10:10:10.000Z"
new Date('2019-12-01T10:10:10Z').toISOString()
"2019-12-01T10:10:10.000Z"
I found the problem. Safari is unable to convert a date string in the format 2019-12-01T10:10:10
into a Date
object without screwing with it. The solution (found here) is to reformat to 2019/12/01 10:10:10
which is supported by all browsers.
// convert into YYYY/MM/DD HH:MM:SS
var dateString = '2019-12-01T10:10:10'.replace(/-/g, '/').replace('T', ' ');
Safari (correct):
new Date(dateString).toISOString()
\\ returns 2019-12-01T09:10:10.000Z
Chrome (correct):
new Date(dateString).toISOString()
\\ returns 2019-12-01T09:10:10.000Z
FireFox (correct):
new Date(dateString).toISOString()
\\ returns 2019-12-01T09:10:10.000Z
Hope this saves the next frustrated developer a couple of hours!