MomentJS - utcOffset() not applying offset?

Viewed 360

I have the following code:

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>

The result of valueUtcOffset is 120.

However, the console.log() returns true and i don't understand why.

value with the UTC offset is 2020-02-11 11PM, whereas thresholdDateWithOffset should be 2020-02-11 10PM.

So how come it says that value is before thresholdDateWithOffset?

2 Answers

Your assumption here is wrong:

value with the UTC offset is 2020-02-11 11PM, whereas thresholdDateWithOffset should be 2020-02-11 10PM.

thresholdDateWithOffset will actually be midnight utc, while value is 11 pm the day before. When you put moment.utc("2020-02-12") you are creating midnight in utc. When you apply the offset moment.utc("2020-02-12").utcOffset(120) it will still be midnight in utc, but represented as "2020-02-12T02:00+02:00". You're just changing the offset the time appears as, you're not really changing the time. The real time used when comparing times remains the same.

The behavior of your snippet is correct. You take timezone which is UTC+2 ( + 120 )

you ask moment to give you a date const thresholdDateWithOffset = moment.utc(thresholdDate).utcOffset(valueUtcOffset); on that timezone.

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

then you check if "2020-02-12T01:00+02:00" is before "2020-02-12T02:00+02:00" and it answered true which is 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
Related