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;
}
请问是如何进行调整方式实现正确的计算;
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…