Date() 对象中的 UTC 日期在 Safari 中输出不同
UTC date in Date() object outputs differently in Safari
var dateString = "2018-01-01T00:00:00";
new Date(dateString);
Chrome、Edge 和 Firefox(右):
Mon Jan 01 2018 00:00:00 GMT-0800 (PST)
Safari(错误):
Sun Dec 31 2017 16:00:00 GMT-0800 (PST)
我该怎么做才能让 Safari 在 1 月 1 日生效?我不想使用 moment.js
或其他框架来解决这个问题。如果你是JavaScriptDate()
对象高手,请指点一下。
谢谢。
一些浏览器以不同方式处理日期字符串。 Mozilla 在他们的 Date
文档页面上记录了这个问题:
Parsing of date strings with the Date constructor (and Date.parse, they are equivalent) is strongly discouraged due to browser differences and inconsistencies. - Source
他们还在 Date.parse()
文档页面上注明了这一点,其中给出了解决方案的提示:
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
如 this answer 中所述,您最好拆分字符串并使用分隔的 Date()
构造函数。示例代码:
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]);
在一个函数中:
function parseDateString(dateString) {
var arr = dateString.split(/\D/);
return new Date(arr[0], arr[1]-1, arr[2], arr[3], arr[4], arr[5]);
}
我希望这能回答你的问题。
var dateString = "2018-01-01T00:00:00";
new Date(dateString);
Chrome、Edge 和 Firefox(右):
Mon Jan 01 2018 00:00:00 GMT-0800 (PST)
Safari(错误):
Sun Dec 31 2017 16:00:00 GMT-0800 (PST)
我该怎么做才能让 Safari 在 1 月 1 日生效?我不想使用 moment.js
或其他框架来解决这个问题。如果你是JavaScriptDate()
对象高手,请指点一下。
谢谢。
一些浏览器以不同方式处理日期字符串。 Mozilla 在他们的 Date
文档页面上记录了这个问题:
Parsing of date strings with the Date constructor (and Date.parse, they are equivalent) is strongly discouraged due to browser differences and inconsistencies. - Source
他们还在 Date.parse()
文档页面上注明了这一点,其中给出了解决方案的提示:
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
如 this answer 中所述,您最好拆分字符串并使用分隔的 Date()
构造函数。示例代码:
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]);
在一个函数中:
function parseDateString(dateString) {
var arr = dateString.split(/\D/);
return new Date(arr[0], arr[1]-1, arr[2], arr[3], arr[4], arr[5]);
}
我希望这能回答你的问题。