瞬间在几个月内的差异
我正在尝试在两个日期之间在几个月中解决差异,而无需考虑几天。
我试图使用 Math.ceil
,但是如果2022年的那一天比2021年的一天领先,那么我得到了2个月而不是1个月的差异。
const diff = moment([2022, 0, 1]).diff(moment([2021, 11, 3]), 'months', true);
console.log(diff); // 0.935483870967742, expected 1
const diffCeil = Math.ceil(
moment([2022, 0, 3]).diff(moment([2021, 11, 1]), 'months', true)
);
console.log('diffCeil', diffCeil); // 2, expected 1
// Inaccurate diff doesn't work when 2021 day is bigger than in 2022
const inacurrateDiff = moment([2022, 0, 3]).diff(moment([2021, 11, 1]), 'months');
console.log('inacurrateDiff', inacurrateDiff); // 1, as expected
const inacurrateDiff2 = moment([2022, 0, 1]).diff(moment([2021, 11, 3]), 'months');
console.log('inacurrateDiff2', inacurrateDiff2); // 0, expected 1
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.3/moment.min.js"></script>
我确实在有没有 diff
的第三个精确
参数的情况下尝试了。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用
startof(d,'月份')
比较几个月的开始:You could use
startOf(d, 'month')
to compare start of months:您会得到2,因为您使用的是
Math.ceil
,它总是将分数值提高到下一个整数。这里没有一个正确的答案,您必须决定要计算的部分月份。
例如,如果仅想要月份,请使用
Math.floor
而不是Math.ceil
。如果您想将最多1.5个月的任何内容计算为一个1.5个月及以上为2的东西,请使用MATH.ROUND
。或者,您可以设置自己的阈值,例如1.2(这要做更多的工作,但没有那么多)。示例:
只有您和您的项目才能说出您要使用的定义。
You get 2 because you're using
Math.ceil
, which always raises the fractional value to the next whole number.There's no one right answer here, you'll have to decide how much of a fractional month you want to count.
For instance, if you want only whole months, use
Math.floor
rather thanMath.ceil
. If you want to count anything up to 1.5 months as one but 1.5 months and above as 2, useMath.round
. Or you could set your own threshold, like 1.2 (it's a bit more work, but not that much).Examples:
Only you and your project can say what definition you want to use.