Files
30-seconds-of-code/snippets/getMonthsDiffBetweenDates.md
2022-12-04 22:20:49 +02:00

689 B

title, tags, author, cover, firstSeen, lastUpdated
title tags author cover firstSeen lastUpdated
Date difference in months date maciv blog_images/two-flower-vases.jpg 2020-08-07T15:15:26+03:00 2020-10-19T22:49:51+03:00

Calculates the difference (in months) between two dates.

  • Use Date.prototype.getFullYear() and Date.prototype.getMonth() to calculate the difference (in months) between two Date objects.
const getMonthsDiffBetweenDates = (dateInitial, dateFinal) =>
  Math.max(
    (dateFinal.getFullYear() - dateInitial.getFullYear()) * 12 +
      dateFinal.getMonth() -
      dateInitial.getMonth(),
    0
  );
getMonthsDiffBetweenDates(new Date('2017-12-13'), new Date('2018-04-29')); // 4