Moment.js月差异 [英] Moment.js months difference

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

问题描述

我现在一直在使用moment.js,这使得日期操作变得容易很多但是我有一个特定的案例失败了,我看不出原因。

I've been using moment.js for a short while now, and it's made date manipulation a lot easier but I have a specific case that is failing, and I can't see why.

在计算今天(2013年10月31日)和2014年2月1日之间的差异时,月份差异为2,尽管两个日期之间有3个完整月份和1天。

When calculating the diff between today (31st October 2013) and the 1st February 2014, the months diff comes back as 2, although there are 3 complete months and one day between the two dates.

10月31日至1月31日期间的差价正常:3个月零天。

Diff between 31st October and 31st January works fine: 3 months and zero days.

var mStartDate = moment([ periodStartDate.getFullYear(), periodStartDate.getMonth(), periodStartDate.getDate() ]);
var mTermDate = moment([ someDate.getFullYear(), someDate.getMonth(), someDate.getDate() ]);

console.log('periodStartDate: ' + periodStartDate);
console.log('someDate: ' + someDate);

// Years
var yearsDiff = mTermDate.diff(mStartDate, 'years');

// Months
var monthsDiff = mTermDate.diff(mStartDate, 'months', true);

控制台记录以下内容:

periodStartDate: Thu Oct 31 2013 11:13:51 GMT+0000 (GMT)
someDate: Sat Feb 01 2014 11:13:51 GMT+0000 (GMT)
monthsDiff: 2

如果我传递true作为布尔值而不是舍入,那么差异就是

If I pass true as the boolean not to round, the months diff is

monthsDiff: 2.983050847457627 

这只是Moment.js.diff()中的一个错误吗?我的其他测试用例中的每一个都成功通过。

Is this just a bug in Moment.js.diff()? Every single one of my other test cases pass successfully.

推荐答案

我认为这与所描述的'特殊处理'有关在精细手册中:

I think this has to do with the 'special handling' as described in The Fine Manual:


经过优化,确保相同日期的两个月是
总是相差整数。

It is optimized to ensure that two months with the same date are always a whole number apart.

所以1月15日到2月15日应该是正好1个月。

So Jan 15 to Feb 15 should be exactly 1 month.

2月28日至3月28日应该是1个月。

Feb 28 to Mar 28 should be exactly 1 month.

2011年2月28日至2月28 2012年应该是1年。

Feb 28 2011 to Feb 28 2012 should be exactly 1 year.

Moment.js在处理 31 Jan时应用此特殊处理 10月31日(同一天):

Moment.js applies this special handling when dealing with 31 Jan and 31 Oct (having the same day):

// 31 Oct 2013 - 1 Feb 2014
> moment([2014, 1, 1]).diff(moment([2013, 9, 31]), 'months', true)
2.983050847457627

// 31 Oct 2013 - 31 Jan 2014
> moment([2014, 0, 31]).diff(moment([2013, 9, 31]), 'months', true)
3

// 31 Oct 2013 - 30 Jan 2014
> moment([2014, 0, 30]).diff(moment([2013, 9, 31]), 'months', true)
2.967741935483871

所以 2.98 值是正确的,只是第二个例子将结果变成'日历月'差异。

So the 2.98 value is correct, it's just that the second example turns the result into a 'calender months' difference.

(关于向下舍入到2,这也记录在同一页面上)

(as for rounding down to 2, that's also documented on the same page)

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

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