Date()对象中的UTC日期在Safari中的输出方式不同 [英] UTC date in Date() object outputs differently in Safari

查看:69
本文介绍了Date()对象中的UTC日期在Safari中的输出方式不同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

var dateString = "2018-01-01T00:00:00";
new Date(dateString);

Chrome,Edge和Firefox(右):

Chrome, Edge and Firefox (right):

Mon Jan 01 2018 00:00:00 GMT-0800 (PST)

Safari(错误):

Safari (wrong):

Sun Dec 31 2017 16:00:00 GMT-0800 (PST)

我该怎么做才能使Safari服从1月1日的义务?我不想使用 moment.js 或其他框架来解决此问题.如果您是JavaScript Date()对象的主人,请向我指出正确的方向.

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.

谢谢.

推荐答案

某些浏览器对日期字符串的处理方式不同.Mozilla在其 Date 文档页面上注意到了此问题:

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

由于浏览器的差异和不一致,强烈建议不要使用Date构造函数(和Date.parse,它们等效)来解析日期字符串.-来源

他们还在他们的 Date.parse()文档页面上注意到了这一点,该页面提供了有关解决方案的提示:

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

不建议使用Date.parse,因为直到ES5为止,字符串的解析完全取决于实现.不同主机解析日期字符串的方式仍存在许多差异,因此应手动解析日期字符串(如果要容纳许多不同格式,则库可以提供帮助).-来源

此答案所述,您可以最好地分割字符串并使用分隔的 Date()构造函数.示例代码:

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]);

在一个功能中:

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.

这篇关于Date()对象中的UTC日期在Safari中的输出方式不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆