简体   繁体   English

UTC 日期之间的 Moment.js 差异

[英]Moment.js diff between UTC dates

I'm using moments.js for working with dates in javascript. All dates are in UTC (or should be).我正在使用moments.js来处理 javascript 中的日期。所有日期都是 UTC(或应该是)。

I have the following date (60 minutes from current time):我有以下日期(从当前时间开始 60 分钟):

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

Now I want to get the difference in seconds between this date and the current UTC datetime, so I do:现在我想得到这个日期和当前 UTC 日期时间之间的秒数差异,所以我这样做:

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

This returns 10800 instead of 3600 , so 3 hours, instead of one.这将返回10800而不是3600 ,所以 3 小时,而不是一个。

Any ideas what I'm doing wrong?任何想法我做错了什么?

Thank you!谢谢!

EDIT:编辑:

I updated the line to seconds = moment().diff(to, 'seconds');我将行更新为seconds = moment().diff(to, 'seconds'); and it gets the currect seconds, but it's -3600 instead of positive.它得到了正确的秒数,但它是-3600而不是正数。

EDIT:编辑:

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 and d2. d1 和 d2。

When I do d1.diff(d2, 'hours', true);当我做d1.diff(d2, 'hours', true); this returns 4 .这返回4 It's definitely something to do with UTC I think, but it seems this should work.我认为这绝对与 UTC 有关,但这似乎应该有效。

This is a legitimate bug.这是一个合法的错误。 I just filed it here: https://github.com/timrwood/moment/issues/261我刚刚在这里提交: 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()

Also, if you need to get the toString of the date, you can use moment().toString() as it proxies to the wrapped Date().toString()此外,如果您需要获取日期的toString ,您可以使用moment().toString()作为包装的Date().toString()的代理

Might be time zones kicking in because you are using toDate() .可能是因为您使用的是时区toDate() Try to just work directly with moment (ie change it to to = moment.utc().add('m', 60); ).尝试直接使用 moment(即将其更改to = moment.utc().add('m', 60); )。

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

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