Check if date is greater than 6 months past

100 views Asked by At

I am trying to check if a date is greater than 6 months past. For example, today is November 7th, 2023. So if I passed the date of May 10, 2023 I would expect it to only return 5 months because it has not yet been 6 months, but it is currently returning 6 months. Is there a better way to accomplish this?

export const diffInMonths = (date: string) => {
   const dateDifference = parseInt(
     DateTime.fromISO(date).diff(DateTime.now(), ['months']).toFormat('M')
   );

   return dateDifference;
};

//this currently returns -6, when in actuality it should be -5 because it has not been 6 months    yet
console.log(diffInMonths('2023-05-10T20:15:00Z'));
1

There are 1 answers

0
Danyil On

The issue you're facing is caused by rounding to the nearest whole month. If you try to convert to days first, calculate the difference, and then divide it back to get the month should work better. Don't forget to do Math.floor() after converting back to month.

Good luck!