Search code examples
javascriptmomentjsmoment-timezone

momentjs - diff() returns wrong time difference


I'm trying to calculate the time until the US/Central midnight. The problem is that my calculation returns 3 hours 30 minutes (as for me in Europe it's 20:30).

moment('2020-12-19 23:59:59', "YYYY-MM-DD HH:mm:ss", 'US/Central') - moment.tz('US/Central')

I think this should work. I'm calculating a difference between US/Central midnight and US/Central now, but it returns the wrong amount of milliseconds.

Do you know how to make it work?

EDIT:

Tried it with diff and still the same result:

moment('2020-12-19 23:59:59', "YYYY-MM-DD HH:mm:ss", 'US/Central').diff(moment.tz('US/Central'),'hours')
> 3

EDIT2:

Tried moment().tz instead of moment.tz and it didn't help at all...

moment('2020-12-19 23:59:59', "YYYY-MM-DD HH:mm:ss", 'US/Central').diff(moment().tz('US/Central'),'hours')
> 3

Solution

  • Maybe try getting the 2 times separately then find another way to check the difference between them. For example

    var now = new Date();
    var midnight = new Date();
    
    midnight.setHours(0,0,0,0); // this set's the midnight var to exactly midnight at your systems timezone, you can then offset that time after this
    

    Then use either moment or some other package to check the difference between the two times.