为什么要将字符串日期转换为日期javascript在chrome中不工作? [英] Why convert string date to date javascript not working in chrome?

查看:121
本文介绍了为什么要将字符串日期转换为日期javascript在chrome中不工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码如下所示:

 < script type =text / javascript> 
var createDate ='2016-07-12 09:09:38';
createDate = createDate.replace(,T);
createDate = new Date(createDate);
console.log(createDate);
< / script>

在Firefox中:日期{Tue Jul 12 2016 09:09:38 GMT在Chrome中: Tue Jul 12 2016 16:09:38 GMT(+0700(东南亚时间))



+0700(东南亚标准时间)



为什么在chrome中结果不同? h2_lin>解决方案

您需要明确地告诉JavaScript您正在存储的日期当前是UTC(与GMT相同)。您可以通过追加 Z 来实现,它代表祖鲁时间。如果你没有指定它,它会回落到浏览器的格式不一致的实现。

  var createDate ='2016-07-12 09:09:38Z'; 
createDate = createDate.replace(,T);
createDate = new Date(createDate);

将变量记录到控制台时,您可能会注意到显示的日期/时间仍然存在差异。请注意,日期/时间是正确的。再次,它涉及浏览器的格式化的实现。您可以确认内部值是正确的:

$ $ $ $ $ codeonsole.log(createDate.toString())
console .log(createDate.toUTCString())



toString() code>将在本地时区返回日期/时间, toUTCString()将以UTC / GMT返回,它应该与您创建的值匹配该对象。


My code is like this :

<script type="text/javascript">
    var createDate = '2016-07-12 09:09:38';
    createDate = createDate.replace(" ", "T");
    createDate = new Date(createDate);
    console.log(createDate);
</script>

In Firefox : Date {Tue Jul 12 2016 09:09:38 GMT+0700 (SE Asia Standard Time)}

In Chrome : Tue Jul 12 2016 16:09:38 GMT+0700 (SE Asia Standard Time)

Why the results are different in chrome?

解决方案

You need to explicitly tell JavaScript that the date you are storing is currently in UTC (which is the same a GMT). You do this by appending Z, which stands for Zulu Time. If you don't specify it, it falls back to the browser's implementation of the format, which is inconsistent.

var createDate = '2016-07-12 09:09:38Z';
createDate = createDate.replace(" ", "T");
createDate = new Date(createDate);

When you log the variable to the Console, you may notice differences between the Date/Time shown still. It's important to note that the Date/Time is correct. Again, it relates to the browser's implementation of the formatting. You can confirm that the internal values are correct with:

console.log(createDate.toString())
console.log(createDate.toUTCString())

The toString() will return the Date/Time in the local Time Zone, and the toUTCString() will return it in UTC/GMT, which should match the value you created the object with.

这篇关于为什么要将字符串日期转换为日期javascript在chrome中不工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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