MomentJS-utcOffset不应用偏移量吗?

问题描述

我有以下代码

const thresholdDate = "2020-02-12";
const value = "2020-02-12T01:00+02:00";

const valueUtcOffset = moment.parseZone(value).utcOffset();

const thresholdDateWithOffset = moment.utc(thresholdDate).utcOffset(valueUtcOffset);

console.log(moment(value).isBefore(thresholdDateWithOffset))
const thresholdDate = "2020-02-12";
const value = "2020-02-12T01:00+02:00";

const valueUtcOffset = moment.parseZone(value).utcOffset();

const thresholdDateWithOffset = moment.utc(thresholdDate).utcOffset(valueUtcOffset);

console.log(moment(value).isBefore(thresholdDateWithOffset))
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.min.js"></script>

valueUtcOffset的结果为120

但是,console.log()返回true,我不明白为什么。

value(具有UTC偏移量)是2020-02-11 11PM,而thresholdDateWithOffset应该是2020-02-11 10PM

那么为什么说valuethresholdDateWithOffset之前呢?

解决方法

您在这里的假设是错误的:

value(具有UTC偏移)是2020-02-11 11PM,而thresholdDateWithOffset应该是2020-02-11 10PM

thresholdDateWithOffset实际上将是UTC的午夜,而value是前一天的晚上11点。当您放置moment.utc("2020-02-12")时,您将在utc中创建午夜。当您应用偏移量moment.utc("2020-02-12").utcOffset(120)时,它在utc中仍将是午夜,但表示为"2020-02-12T02:00+02:00"。您只是在更改时间的偏移量,您实际上并没有更改时间。比较时间时使用的实时时间保持不变。

,

您的代码段行为正确。 您采用的时区为UTC + 2(+ 120)

您要求moment在该时区给您一个日期const thresholdDateWithOffset = moment.utc(thresholdDate).utcOffset(valueUtcOffset);

const thresholdDateWithOffset = moment.utc(thresholdDate).utcOffset(valueUtcOffset); //"2020-02-12T02:00+02:00"

然后您检查"2020-02-12T01:00+02:00"是否在"2020-02-12T02:00+02:00"之前,并且回答为true,这是真的

moment.utc("2020-02-12") => 2020-02-12T00:00+00:00
moment.utc("2020-02-12").utcOffset(120) => 2020-02-12T02:00+02:00



moment.utc("2020-02-12T00:00+02:00") => 2020-02-11T10:00+00:00
moment.utc("2020-02-12T00:00+02:00").utcOffset(120) => 2020-02-12T00:00+02:00