将今天的日期与当前的另一个日期进行比较会返回错误的日期,为什么呢? [英] Comparing today's date with another date in moment is returning the wrong date, why?

查看:156
本文介绍了将今天的日期与当前的另一个日期进行比较会返回错误的日期,为什么呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 moment.js 1.7.0尝试将今天的日期与另一个日期(函数表示由于某种原因,它们相距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对象,就像由new Date(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.

这篇关于将今天的日期与当前的另一个日期进行比较会返回错误的日期,为什么呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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