Moment.js在UTC之间的差异 [英] Moment.js diff between UTC dates

查看:492
本文介绍了Moment.js在UTC之间的差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 moments.js 使用JavaScript中的日期。所有日期均为UTC(或应为)。

I'm using moments.js for working with dates in javascript. All dates are in UTC (or should be).

我有以下日期(从当前时间起60分钟):

I have the following date (60 minutes from current time):

//Wed, 04 Apr 2012 21:09:16 GMT
to   = moment.utc().add('m', 60).toDate();

现在我想得到这个日期和当前UTC日期时间之间的秒数,所以我做:

Now I want to get the difference in seconds between this date and the current UTC datetime, so I do:

seconds = moment.utc().diff(to, 'seconds');

这将返回 10800 而不是 3600 ,所以3个小时,而不是一个。

This returns 10800 instead of 3600, so 3 hours, instead of one.

任何想法我做错了什么?

Any ideas what I'm doing wrong?

谢谢!

编辑:

code> seconds = moment()。diff(to,'seconds'); ,它会获得正确的秒数,但它是 -3600 而不是积极的。

I updated the line to seconds = moment().diff(to, 'seconds'); and it gets the currect seconds, but it's -3600 instead of positive.

编辑:

我现在有这两个时刻的对象:

I now have these two moment objects:

{ _d: Thu, 05 Apr 2012 17:33:18 GMT, _isUTC: true }
{ _d: Thu, 05 Apr 2012 16:38:45 GMT, _isUTC: true }

d1和d2。

当我执行 d1.diff(d2,'hours',true); 这将返回 4 。这肯定是与UTC相关的,我认为,但似乎这个应该工作。

When I do d1.diff(d2, 'hours', true); this returns 4. It's definitely something to do with UTC I think, but it seems this should work.

推荐答案

是一个合法的bug。我刚刚在这里提交: https://github.com/timrwood/moment/issues/261

This is a legitimate bug. I just filed it here: https://github.com/timrwood/moment/issues/261

要解决这个问题,请使用以下代码:

To get around it, use the following instead.

var a = moment.utc().add('m', 60).toDate(),
    b = moment().diff(to, 'seconds'); // use moment() instead of moment.utc()

另外,如果你需要得到 toString 的日期,您可以使用 moment()。toString()代替包裹的 Date()。toString()

Also, if you need to get the toString of the date, you can use moment().toString() as it proxies to the wrapped Date().toString()

这篇关于Moment.js在UTC之间的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆