如何禁用moment.js日光时区转换

时间:2016-06-13 19:40:21

标签: javascript angularjs node.js datetime momentjs

可以在moment.js?

中禁用日光时区转换

http://plnkr.co/edit/MjFelt?p=preview

      $scope.obj.date = moment('2016-06-03T04:00:00.000Z');

基本上我的应用程序仅处理事件和日期,但转换夏令时的moment.js导致日期问题。是否有任何设置会在整个应用程序使用期间禁用它?

2 个答案:

答案 0 :(得分:7)

如果您想要时刻显示您的日期和时间(即UTC,如' Z'所示),那么您应该使用moment.utc:

moment.utc('2016-06-03T04:00:00.000Z').format()
"2016-06-03T04:00:00Z"

当你使用默认时刻构造函数时,就像现在一样,你想知道将UTC时间转换为当地时间的时刻,这就是你看到时差的原因。例如,在我的本地机器上(我目前是UTC-5),我得到以下内容:

moment('2016-06-03T04:00:00.000Z').format()
"2016-06-02T23:00:00-05:00"

这个问题出现了很多,所以我写了这篇博文,解释了时刻的构造函数以及它如何详细转换ISO8601日期:https://maggiepint.com/2016/05/14/moment-js-shows-the-wrong-date/

答案 1 :(得分:0)

就我而言,由于“夏令时”,我更改了时区。

我下一个时期是

{
    "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. dont sure that it required
    .utcOffset(currentTzOffset) // put your tz to here
    .format(yourDateFormat);
const endToLocalZone = moment(to, yourDateFormat)
    .local() // just checking. dont sure that it required
    .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 '