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

一曲冷凌霜 提交于 2021-02-08 08:13:20

问题


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"

回答1:


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


来源:https://stackoverflow.com/questions/36797014/javascript-moment-timezone-difference-between-dates-in-different-time-zones

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!