moment.js diff 计算相差浮点数月份时间存在问题
moment('2020-11-01',"YYYY-MM-DD").diff(moment('2020-10-01',"YYYY-MM-DD"), 'months',true).toFixed(4); // 1
moment('2020-10-31',"YYYY-MM-DD").diff(moment('2020-10-01',"YYYY-MM-DD"), 'months',true).toFixed(4); // 0.9677
moment('2020-10-30',"YYYY-MM-DD").diff(moment('2020-10-01',"YYYY-MM-DD"), 'months',true).toFixed(4); // 0.9667
moment('2020-10-29',"YYYY-MM-DD").diff(moment('2020-10-01',"YYYY-MM-DD"), 'months',true).toFixed(4); // 0.9333
moment('2020-10-02',"YYYY-MM-DD").diff(moment('2020-10-01',"YYYY-MM-DD"), 'months',true).toFixed(4); // 0.0333
从上面的结果来看计算部分存在问题,10月份总共31天,1天应该是 1/31 ≈ 0.0323,使用moment.js计算出来结果不符合,
// moment.js 原装方法
function monthDiff (a, b) {
// difference in months
var wholeMonthDiff = ((b.year() - a.year()) * 12) + (b.month() - a.month()),
// b is in (anchor - 1 month, anchor + 1 month)
anchor = a.clone().add(wholeMonthDiff, 'months'),
anchor2, adjust;
if (b - anchor < 0) {
anchor2 = a.clone().add(wholeMonthDiff - 1, 'months');
// linear across the month
adjust = (b - anchor) / (anchor - anchor2);
} else {
anchor2 = a.clone().add(wholeMonthDiff + 1, 'months');
// linear across the month
adjust = (b - anchor) / (anchor2 - anchor);
}
//check for negative zero, return zero if negative zero
return -(wholeMonthDiff + adjust) || 0;
}
请问是如何进行调整方式实现正确的计算;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论