Javascript UTC 日期之间的 Moment.js 差异
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10018575/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Moment.js diff between UTC dates
提问by dzm
I'm using moments.jsfor working with dates in javascript. All dates are in UTC (or should be).
我正在使用moment.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 小时,而不是 1 小时。
Any ideas what I'm doing wrong?
任何想法我做错了什么?
Thank you!
谢谢!
EDIT:
编辑:
I updated the line to seconds = moment().diff(to, 'seconds');
and it gets the currect seconds, but it's -3600
instead of positive.
我更新了该行seconds = moment().diff(to, 'seconds');
并获得了当前秒数,但它-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);
this returns 4
. It's definitely something to do with UTC I think, but it seems this shouldwork.
当我这样做时d1.diff(d2, 'hours', true);
返回4
. 我认为这绝对与 UTC 有关,但似乎这应该可行。
回答by timrwood
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()
回答by Supr
Might be time zones kicking in because you are using toDate()
. Try to just work directly with moment (i.e. change it to to = moment.utc().add('m', 60);
).
可能是时区启动,因为您正在使用toDate()
. 尝试直接使用 moment(即,将其更改为to = moment.utc().add('m', 60);
)。