【问题标题】:How do I get ISO8601 string with time offset in JavaScript?如何在 JavaScript 中获取带有时间偏移的 ISO8601 字符串?
【发布时间】:2015-10-13 09:27:01
【问题描述】:
【问题讨论】:
标签:
javascript
date
iso8601
【解决方案1】:
那么有什么好的方法可以实现我的日期格式吗?
如果您想要具有偏移量的本地时间 ISO-8601 版本,您所能做的就是使用getDay、getMonth 等的非 UTC 版本,从 getTimezoneOffset 获取时区偏移量,然后自己构建字符串。 (或者使用 MomentJS 之类的库。)规范中没有任何内容可以做到这一点。
【解决方案2】:
是否有好的方法取决于。事实上,没有内置的方法可以做到这一点。但是你可以通过使用Date.getTimezoneOffset() 和做一些modulus 自己构建一个。这是一条线索:
// set up date 2009-02-13T23:31:30.123Z (equivalent to 1234567890123 milliseconds):
var localDate = new Date(1234567890123);
// get local time offset, like -120 minutes for CEST (UTC+02:00):
var offsetUTC = new Date().getTimezoneOffset();
// set date to local time:
localDate.setMinutes(localDate.getMinutes() - offsetUTC);
offsetUTC = {
// positive sign unless offset is at least -00:30 minutes:
"s": offsetUTC < 30 ? '+' : '-',
// local time offset in unsigned hours:
"h": Math.floor(Math.abs(offsetUTC) / 60),
// local time offset minutes in unsigned integers:
"m": ~~Math.abs(offsetUTC) % 60
};
offsetUTC = offsetUTC.s + // explicit offset sign
// unsigned hours in HH, dividing colon:
('0'+Math.abs(offsetUTC.h)+':').slice(-3) +
// minutes are represented as either 00 or 30:
('0'+(offsetUTC.m < 30 ? 0 : 30)).slice(-2);
localDate = localDate.toISOString().replace('Z',offsetUTC);
// === "2009-02-13T23:31:30.123+02:00" (if your timezone is CEST)
或者不那么冗长:
localDate = localDate.toISOString().replace('Z',(offsetUTC<30?'+':'-')+
('0'+Math.floor(Math.abs(offsetUTC)/60)+':').slice(-3)+
('0'+((~~Math.abs(offsetUTC)%60)<30?0:30)).slice(-2));
请注意……