Chrome 与 Firefox 中的 Javascript 日期不正确

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17334602/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 07:55:28  来源:igfitidea点击:

Incorrect Javascript Date in Chrome vs Firefox

javascriptgoogle-chromefirefoxdate

提问by jaekie

I'm getting incorrect dates in Chrome...

我在 Chrome 中收到错误的日期...

My code looks like this..

我的代码看起来像这样..

Title contains "2013-06-14T00:00:00", it was a DateTime in C# returned from WebAPI

标题包含“2013-06-14T00:00:00”,它是从 WebAPI 返回的 C# 中的 DateTime

As you can see here on both browsers.. enter image description here

正如您在两个浏览器上看到的那样.. 在此处输入图片说明

When I add it to a new javascript date like this.. var dt = new Date(title)

当我将它添加到这样的新 javascript 日期时.. var dt = new Date(title)

I get different dates in different browsers... enter image description here

我在不同的浏览器中得到不同的日期... 在此处输入图片说明

Example - http://jsfiddle.net/RvUSq/

示例 - http://jsfiddle.net/RvUSq/

采纳答案by Diode

Convert timestamp to ISO 8601formatted string in C#, for e.g

在 C# 中将时间戳转换为ISO 8601格式的字符串,例如

var title = "14 JUN 2013 00:00:00" // printed from C#

Then use Dateconstructor

然后使用Date构造函数

var date = new Date(title);

If you don't specify timezone the local timezone in the client machine will be set to the given time. If you specify the timezone, needed calculations will be done to convert the date to local timezone.

如果您不指定时区,则客户端计算机中的本地时区将设置为给定时间。如果您指定时区,将完成所需的计算以将日期转换为本地时区。

var title = "14 JUN 2013 00:00:00";
var date = new Date(title); // Fri Jun 14 2013 00:00:00 GMT+0530 (IST)

var title = "14 JUN 2013 00:00:00 GMT";
var date = new Date(title); // Fri Jun 14 2013 05:30:00 GMT+0530 (IST)

var title = "14 JUN 2013 00:00:00 GMT-0400";
var date = new Date(title); // Fri Jun 14 2013 09:30:00 GMT+0530 (IST)

ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse

参考:https: //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse

回答by Ye Liu

Looks like Firefox is assuming this datetime format without timezone is local time and Chrome/Webkit is assuming it's UTC.

看起来 Firefox 假设这种没有时区的日期时间格式是本地时间,而 Chrome/Webkit 假设它是 UTC。

If the datetime returned from the api is UTC, simply append a "Z" to the end of the string, so it becomes "2013-06-14T00:00:00Z", which indicates the time is in UTC, then you will get the same result in the two browsers.

如果从api返回的日期时间是UTC,只需在字符串末尾附加一个“Z”,就变成“2013-06-14T00:00:00Z”,表示时间是UTC,那么你会得到在两个浏览器中的结果相同。