Andrew
Andrew

Reputation: 2198

Javascript moment - timezone, difference between dates in different time zones

I have:

var now = moment.format(); //get current time
var days = 5; //days I need to subtract from time(then)
var then = '05/02/2016 12:00 am';

Now I need to get difference between now and then substract(-) 5 days but in +0000 so GMT +0. so now must be in user localtime and then must be at +0000 GMT.

How I can get difference between this dates in days, hours, minutes, seconds?

I try:

var now  = moment().format();                         
var then = moment('05/02/2016 12:00 am').utcOffset(+0000).format(); 
    then = moment(then).subtract(5,'days');
    d = moment.utc(moment(now).diff(moment(then))).format("DD HH:mm:ss");

but I get result- which is wrong...

"27 18:48:55"

Upvotes: 1

Views: 3089

Answers (1)

Dogbert
Dogbert

Reputation: 222188

The problem is that you're trying to use a time difference as a time. You need to use moment.duration() with the return value of the diff. You should also call then.diff(now) to get a positive difference. There were also some unnecessary calls to .format() and moment() that I removed.

var now  = moment();
var then = moment('05/02/2016 12:00 am').utcOffset(+0000).subtract(5, 'days');
var duration = moment.duration(then.diff(now));
console.log(duration.days(), duration.hours(), duration.minutes(), duration.seconds());

logs

4 3 15 46

Upvotes: 1

Related Questions