目标:找到本地时间
和UTC时间偏移量
,然后按照以下格式构建URL。
示例 URL:/Actions/Sleep?duration=2002-10-10T12:00:00−05:00
格式基于W3C recommendation .文档说:
For example, 2002-10-10T12:00:00−05:00 (noon on 10 October 2002, Central Daylight Savings Time as well as Eastern Standard Time in the U.S.) is equal to 2002-10-10T17:00:00Z, five hours later than 2002-10-10T12:00:00Z.
因此,根据我的理解,我需要通过 new Date()
找到我的本地时间,然后使用 getTimezoneOffset()
函数计算差值,然后将其附加到字符串结束。
使用
格式
获取本地时间var local = new Date().format("yyyy-MM-ddThh:mm:ss"); // 2013-07-02T09:00:00
按小时获取 UTC 时间偏移量
var offset = local.getTimezoneOffset() / 60; // 7
构造URL(仅限时间部分)
var duration = local + "-" + offset + ":00"; // 2013-07-02T09:00:00-7:00
上面的输出表示我的本地时间是 2013/07/02 早上 9 点,与 UTC 相差 7 小时(UTC 比本地时间提前 7 小时)
到目前为止它似乎有效,但如果 getTimezoneOffset()
返回负值(如 -120)怎么办?
我想知道在这种情况下格式应该是什么样子,因为我无法从 W3C 文档中弄清楚。
最佳答案
这是一个简单的辅助函数,可以为您格式化 JS 日期。
function toIsoString(date) {
var tzo = -date.getTimezoneOffset(),
dif = tzo >= 0 ? '+' : '-',
pad = function(num) {
return (num < 10 ? '0' : '') + num;
};
return date.getFullYear() +
'-' + pad(date.getMonth() + 1) +
'-' + pad(date.getDate()) +
'T' + pad(date.getHours()) +
':' + pad(date.getMinutes()) +
':' + pad(date.getSeconds()) +
dif + pad(Math.floor(Math.abs(tzo) / 60)) +
':' + pad(Math.abs(tzo) % 60);
}
var dt = new Date();
console.log(toIsoString(dt));
关于javascript - 如何在 JavaScript 中使用 ISO 8601 格式化带有时区偏移的日期?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17415579/