【问题标题】:how to disable moment.js daylight timezone conversion如何禁用 moment.js 日光时区转换
【发布时间】:2016-10-14 08:27:42
【问题描述】:
可以在 moment.js 中禁用夏令时时区转换吗?
http://plnkr.co/edit/MjFelt?p=preview
$scope.obj.date = moment('2016-06-03T04:00:00.000Z');
基本上,我的应用程序只处理事件和日期,但是转换夏令时的 moment.js 会导致日期问题。它是否有任何设置会在整个应用程序使用过程中禁用它?
【问题讨论】:
标签:
javascript
angularjs
node.js
datetime
momentjs
【解决方案1】:
如果您说要让 moment 显示您的日期和时间(这是 UTC,由“Z”表示),您应该使用 moment.utc:
moment.utc('2016-06-03T04:00:00.000Z').format()
"2016-06-03T04:00:00Z"
当您使用默认的 moment 构造函数时,就像现在一样,您正在告诉 moment 将您的 UTC 时间转换为本地时间,这就是您看到时差的原因。例如,在我的本地机器上(我目前是 UTC-5)我得到以下信息:
moment('2016-06-03T04:00:00.000Z').format()
"2016-06-02T23:00:00-05:00"
这个问题出现了很多,所以我写了这篇博文,详细解释了 moment 的构造函数以及它如何转换 ISO8601 日期:https://maggiepint.com/2016/05/14/moment-js-shows-the-wrong-date/
【解决方案2】:
就我而言,时区因“夏令时”而改变时遇到了问题。
我有下一个时期:
{
"from": "2020-10-01 00:00:00 +0200",
"to":"2020-11-01 00:00:00 +0100",
}
而我想得到:
{
"from": "2020-10-01 00:00:00 +0200",
"to":"2020-11-01 00:00:00 +0200",
}
我的解决方案是获取当前(本地)时区并将其设置为两个日期时刻:
const currentTzOffset = moment().utcOffset(); // getting current timezone offset
const startToLocalZone = moment(from, yourDateFormat)
.local() // just checking. not sure if this is necessary
.utcOffset(currentTzOffset) // put your tz to here
.format(yourDateFormat);
const endToLocalZone = moment(to, yourDateFormat)
.local() // just checking. not sure if this is necessary
.utcOffset(currentTzOffset) // put your tz to here
.format(yourDateFormat);
console.log(startToLocalZone); // output: "2020-10-01 00:00:00 +0200"
console.log(endToLocalZone); // output: "2020-11-01 00:00:00 +0200"
并且不要忘记设置您的日期格式而不是'yourDateFormat'