最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Safari returns incorrect value for Date toISOString() - Stack Overflow

programmeradmin0浏览0评论

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?

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?

Share Improve this question edited Apr 20, 2023 at 18:43 John Doherty asked Feb 16, 2019 at 18:30 John DohertyJohn Doherty 4,08539 silver badges40 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 21

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!

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"
发布评论

评论列表(0)

  1. 暂无评论