简体   繁体   English

Javascript moment-时区,不同时区中的日期之间的差异

[英]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. 现在我需要之间取得差异nowthen 。减去( - )5-天,但在如此+0000 GMT +0。 so now must be in user localtime and then must be at +0000 GMT. 因此now必须位于用户本地时间, then必须位于格林尼治标准时间+0000。

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"

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 . 您需要使用带有diff返回值的moment.duration() You should also call then.diff(now) to get a positive difference. 您还应该调用then.diff(now)以获得正差​​。 There were also some unnecessary calls to .format() and moment() that I removed. 我删除了对.format()moment()一些不必要的调用。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM