Moment.js diff between UTC dates

Go To StackoverFlow.com

16

I'm using moments.js for working with dates in javascript. All dates are in UTC (or should be).

I have the following date (60 minutes from current time):

//Wed, 04 Apr 2012 21:09:16 GMT
to   = moment.utc().add('m', 60).toDate();

Now I want to get the difference in seconds between this date and the current UTC datetime, so I do:

seconds = moment.utc().diff(to, 'seconds');

This returns 10800 instead of 3600, so 3 hours, instead of one.

Any ideas what I'm doing wrong?

Thank you!

EDIT:

I updated the line to seconds = moment().diff(to, 'seconds'); and it gets the currect seconds, but it's -3600 instead of positive.

EDIT:

I now have these two moment objects:

{ _d: Thu, 05 Apr 2012 17:33:18 GMT, _isUTC: true }
{ _d: Thu, 05 Apr 2012 16:38:45 GMT, _isUTC: true }

d1 and d2.

When I do d1.diff(d2, 'hours', true); this returns 4. It's definitely something to do with UTC I think, but it seems this should work.

2012-04-04 20:13
by dzm


17

This is a legitimate bug. I just filed it here: https://github.com/timrwood/moment/issues/261

To get around it, use the following instead.

var a = moment.utc().add('m', 60).toDate(),
    b = moment().diff(to, 'seconds'); // use moment() instead of moment.utc()

Also, if you need to get the toString of the date, you can use moment().toString() as it proxies to the wrapped Date().toString()

2012-04-06 06:19
by timrwood
Just FYI, this was fixed in version 1.6.0 - timrwood 2012-05-02 19:52
The bug still exists when dealing with Summer Time. Example: Difference in days between 15/10/2017 and 22/10/2017 (UTC). First date is not in Brazilian Summer Time, but the second is. The fix you suggested above did the trick - Joaobrunoah 2017-10-17 12:56


0

Might be time zones kicking in because you are using toDate(). Try to just work directly with moment (i.e. change it to to = moment.utc().add('m', 60);).

2012-04-04 20:42
by Supr
Hm, that 'to' is really a value coming from the database, that was created using the code above, so I have to use toDate() to get the string to store - dzm 2012-04-04 21:30
@Super I edited the post. Working with moment objects that are UTC, getting similar issues - dzm 2012-04-05 16:42
Ads