moment.js差异不正确 [英] moment.js diff incorrect

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

问题描述

我正在使用 moment.js 1.7.0尝试将今天的日期与另一个日期进行比较,但 diff 函数说它们因某种原因相隔1天。

I'm using moment.js 1.7.0 to try and compare today's date with another date but the diff function is saying they are 1 day apart for some reason.

代码

var releaseDate = moment("2012-09-25");
var now = moment(); //Today is 2012-09-25, same as releaseDate  
console.log("RELEASE: " + releaseDate.format("YYYY-MM-DD"));
console.log("NOW: " + now.format("YYYY-MM-DD"));
console.log("DIFF: " + now.diff(releaseDate, 'days'));

控制台

RELEASE: 2012-09-25
NOW: 2012-09-25
DIFF: 1 

创意?

推荐答案

基于文档(和简要测试),moment.js创建了约会对象的包装器。声明:

Based on the documentation (and brief testing), moment.js creates wrappers around date objects. The statement:

var now = moment();

创建一个时刻对象,其核心部分创建了一个新的Date对象,就像 new Date(),因此小时,分钟和秒将设置为当前时间。

creates a "moment" object that at its heart has a new Date object created as if by new Date(), so hours, minutes and seconds will be set to the current time.

声明:

var releaseDate = moment("2012-09-25");

创建一个时刻对象,其核心部分创建了一个新的Date对象,就像<$ c $一样c>新日期(2012年,8月25日)其中小时,分钟和秒将全部设置为当地时区的零。

creates a moment object that at its heart has a new Date object created as if by new Date(2012, 8, 25) where the hours, minutes and seconds will all be set to zero for the local time zone.

moment.diff 根据两个日期之间的舍入差异(以毫秒为单位)返回一个值。要查看完整值,请将 true 作为第三个参数传递:

moment.diff returns a value based on a the rounded difference in ms between the two dates. To see the full value, pass true as the third parameter:

 now.diff(releaseDate, 'days', true)
 ------------------------------^

因此它将取决于代码运行的时间和本地时区是否 now.diff(releaseDate,'days')即使在相同的本地日期运行也是零或一。

So it will depend on the time of day when the code is run and the local time zone whether now.diff(releaseDate, 'days') is zero or one, even when run on the same local date.

如果你想比较日期,然后使用:

If you want to compare just dates, then use:

var now = moment().startOf('day'); 

将时间设置为当地时区的00:00:00。

which will set the time to 00:00:00 in the local time zone.

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

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