javascript - 解析 ISO 8601 日期字符串时如何假定本地时区?

标签 javascript

我有一个 ISO 日期字符串,如下所示

 var startTimeISOString = "2013-03-10T02:00:00Z";

当我使用下面的代码将其转换为 JavaScript 中的日期对象时,它会返回

var startTimeDate = new Date(startTimeISOString);

输出为

Date {Sun Mar 10 2013 07:30:00 GMT+0530 (India Standard Time)}

它确实会将 ISOString 转换为日期,但它会转换为本地时间,因为 new Date() 取决于客户端。如何将 iso 日期时间字符串转换为日期和时间,而不转换为本地日期时间..?

谢谢

最佳答案

<强> According to MDN :

Differences in assumed time zone

Given a date string of "March 7, 2014", parse() assumes a local time zone, but given an ISO format such as "2014-03-07" it will assume a time zone of UTC. Therefore Date objects produced using those strings will represent different moments in time unless the system is set with a local time zone of UTC. This means that two date strings that appear equivalent may result in two different values depending on the format of the string that is being converted (this behavior is changed in ECMAScript ed 6 so that both will be treated as local).

我已经这样做了,现在得到的是 ISO 日期字符串中的确切时间,而不是本地时间

 var startTimeISOString = "2013-03-10T02:00:00Z";

 var startTime = new Date(startTimeISOString );
 startTime =   new Date( startTime.getTime() + ( startTime.getTimezoneOffset() * 60000 ) );

这将在 iso 日期字符串中给出相同的日期时间,这里的输出是

o/p

Date {Sun Mar 10 2013 02:00:00 GMT+0530 (India Standard Time)}

关于javascript - 解析 ISO 8601 日期字符串时如何假定本地时区?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15517024/

相关文章:

javascript - 使用 navigator.sendBeacon 注销用户时出现错误 404

javascript - JQuery - 使用 .html() 设置后获取 .html()

javascript - 尝试 click() 一个没有 onclick 事件的按钮

javascript - 有没有一种方法可以将 Slick-Carousel 与 Polymer.js 一起使用?

javascript - 如何使用 jqGrid editoptions 值的函数创建有效的字符串?

javascript - 有什么方法可以知道用户是否接到电话? (Javascript)

javascript - 从 javascript 函数调用 razor c# 函数

php - 文本区域中最多允许 2 个换行符

javascript - 从html输入文本框内按回车键时如何防止回发?

javascript - 如何使用 Javascript 和/或 Jquery 删除本地存储中对象中的键?