skip to Main Content

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'));

2

Answers


  1. 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!

    Login or Signup to reply.
  2. The issue with the provided method is that it’s rounding the difference to the nearest whole number of months. When you’re asking for the difference in a singular unit like ‘months’, Luxon (assuming DateTime refers to Luxon’s DateTime object) calculates the entire difference in terms of that unit, which can lead to rounding.

    To accurately determine if the date is more than 6 months in the past without rounding, you’ll need to compare the difference in months and then check the day of the month to ensure a full 6 months have passed. Here’s how you can do this:

    import { DateTime } from 'luxon';
    
    export const diffInMonths = (date: string) => {
      const now = DateTime.now();
      const pastDate = DateTime.fromISO(date);
      const monthsDifference = now.month - pastDate.month 
                             + (now.year - pastDate.year) * 12;
    
      // Check if an additional month has not fully passed
      if (pastDate.day > now.day) {
        return monthsDifference - 1;
      }
    
      return monthsDifference;
    };
    
    console.log(diffInMonths('2023-05-10T20:15:00Z'));
    

    With this function, if the pastDate is May 10, 2023, and the current date is November 7, 2023, it will calculate the month difference as 6 (from May to November), but then it will check the day and adjust the difference to 5 since November 7 is not a full month past May 10.

    Make sure to adjust this function if you want to account for time zones or other considerations. The current function assumes that the provided date is in the same time zone as the server’s local time. If you need to compare dates in UTC or a specific time zone, you will need to modify the DateTime.now() to use the same time zone as the input date.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search