momentjs date comparison with timezone

Viewed 2131

I have been using momentjs and moment-timezone for a while. While using date comparison using isAfter method today, I discovered strange behaviour.

Suppose one moment date is configured with timezone value and other isn't then what should be the behaviour of date comparison?

In my case, we are converting an epoch time to specific timezone value for one date. Other date is in format yyyy-mm-dd without any timezone value. When I am comparing these two days, it is failing for same day value.

//Wed Sep 27 2017 01:13:04 GMT-0700
var localtime = moment(1506499984924).tz("America/Los_Angeles");

//Wed Sep 27 2017 00:00:00
var date = moment('2017-09-27');

//returns true
var value = localtime.isAfter(date, 'day');

Ideally since both dates are Sept 27 2017, it should return false. Using diff method instead isAfter returns 0 which is true.

Any help is appreciated to solve this issue.

I have created a pen with this code: Moment

1 Answers

In your code:

var date = moment('2017-09-27');

This create a value at midnight local time. How that relates to a specific instant in time is highly dependent on which local time zone your computer is set to.

Moment objects are always compared as moments - that is, instantaneous values based on UTC.

I see false when I run your code pen because I am in a time zone that is behind UTC. If you see true, it's because you are in a local time zone that is ahead of UTC (by over an hour, given the time of the other value).

Related