简体   繁体   English

Chrome与Firefox中的Javascript日期不正确

[英]Incorrect Javascript Date in Chrome vs Firefox

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.. 正如你在这两个浏览器上看到的那样.. 在此输入图像描述

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... 我在不同的浏览器中得到不同的日期 在此输入图像描述

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

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,然后你会得到两个浏览器的结果相同。

Convert timestamp to ISO 8601 formatted string in C#, for eg 例如,将时间戳转换为C#中的ISO 8601格式化字符串

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

Then use Date constructor 然后使用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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM