【问题标题】:Javascript moment - timezone, difference between dates in different time zonesJavascript时刻 - 时区,不同时区日期之间的差异
【发布时间】:2016-08-16 06:32:59
【问题描述】:

我有:

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';

现在我需要得到 nowthen 之间的差异 5 天但在 +0000 所以 GMT +0。 所以now 必须是用户本地时间,then 必须是 +0000 GMT。

我怎样才能得到这些日期之间的天、小时、分钟、秒的差异?

我试试:

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");

但我得到了结果——这是错误的......

"27 18:48:55"

【问题讨论】:

  • 是 5 月 2 日还是 2 月 5 日?
  • 预期结果是什么?
  • 预期结果将在 now() 和 4 月 27 日之间的天数、小时数、分钟数上有所不同(因为 2.May - 5 天 = 27. April)
  • 那么,您是否想要现在的本地时间和五天前的时间,但使用UTC?我不明白持续时间在这方面有多重要。这两件事总是相隔五天。你能稍微澄清一下吗?
  • 我可能以最好的方式解决了这个问题,但工作正常: var tz = new Date().getTimezoneOffset()/60*(-1); var now = moment.utc(); var dod = parseInt('{{$article->auction_end}}')-1; var then = moment.utc(obj.start).utcOffset(+0000).subtract(dod, 'days'); then = moment(then).add(tz,'hours'); var duration = moment.duration(then.diff(now)); d = duration.days()+'d'+duration.hours()+'h'+duration.minutes()+'m'+duration.seconds();

标签: javascript date momentjs difference gmt


【解决方案1】:

问题是您试图使用时差作为时间。您需要将moment.duration()diff 的返回值一起使用。您还应该致电then.diff(now) 以获得积极的差异。还有一些对.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());

日志

4 3 15 46

【讨论】:

  • 我认为这是个问题,非常感谢您的帮助
  • 嗯,现在 GMT 有问题...因为来自 Dubaigmt +4 的人和来自欧洲的人没有得到相同的区别
  • 我创建拍卖,并且每个时区的拍卖必须同时结束,所以来自亚洲的用户必须获得 (4h 33m),但来自欧洲的用户必须获得 (4h 33m),来自美国的用户必须获得 ( 4h 33m) ... 因为我需要获得 +0 时间并计算差异,因为 +0 时间到处都是一样的。
  • @Andrew 我想你想要的是moment('05/02/2016 12:00 am').utcOffset(+0000),而不是moment.utc('05/02/2016 12:00 am')
  • 您还需要指定格式。您现在正在回退到 JS 日期构造,您应该会收到弃用警告。这不是你想要的,它可能会导致不可预知的结果。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-16
相关资源
最近更新 更多