I am trying to work out a difference in months between two dates without taking days into consideration.
I was trying to use Math.ceil
but if the day in 2022 was ahead of the one in 2021 then I got 2 months instead of 1 month difference.
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>
I did try it with and without diff
's third precise
parameter.