Difference between two dates in years, months, days in JavaScript

前端 未结 26 2467
执念已碎
执念已碎 2020-11-22 07:18

I\'ve been searching for 4 hours now, and have not found a solution to get the difference between two dates in years, months, and days in JavaScript, like: 10th of April 201

26条回答
  •  孤街浪徒
    2020-11-22 07:53

    With dayjs we did it in that way:

    export const getAgeDetails = (oldDate: dayjs.Dayjs, newDate: dayjs.Dayjs) => {
      const years = newDate.diff(oldDate, 'year');
      const months = newDate.diff(oldDate, 'month') - years * 12;
      const days = newDate.diff(oldDate.add(years, 'year').add(months, 'month'), 'day');
    
      return {
        years,
        months,
        days,
        allDays: newDate.diff(oldDate, 'day'),
      };
    };
    

    It calculates it perfectly including leap years and different month amount of days.

提交回复
热议问题