我有一个 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/