Skip to content

JavaScript difference between two dates in years months days

  • by

Learn how to calculate the difference between two dates in years, months, and days using JavaScript. You can follow the steps below:

  1. Create two date objects using the Date() constructor.
  2. Calculate the difference between the two dates in milliseconds using the getTime() method.
  3. Convert the difference to days using division by the number of milliseconds in a day (1000 * 60 * 60 * 24).
  4. Calculate the number of years by dividing the number of days by 365 (or 366 for leap years).
  5. Calculate the number of months by dividing the number of days by 30.44 (the average number of days in a month).
  6. Calculate the remaining days by subtracting the number of years and months from the total number of days.

JavaScript difference between two dates in years months days example

Simple example code getDateDiffInYMD() function takes two date objects as parameters, and returns an object containing the number of years, months, and days between them. The Math.floor() method is used to round down the results of division to the nearest integer.

<!DOCTYPE html>
<html>
<body>
<script>
    function getDateDiffInYMD(startDate, endDate) {
    const oneDayMs = 1000 * 60 * 60 * 24;
    const diffMs = endDate.getTime() - startDate.getTime();
    const diffDays = Math.floor(diffMs / oneDayMs);
    const years = Math.floor(diffDays / 365);
    const months = Math.floor(diffDays / 30.44) % 12;
    const days = diffDays - (years * 365) - (Math.floor(months * 30.44));
        return { years, months, days };
    }

    const startDate = new Date('2022-10-01');
    const endDate = new Date('2023-12-27');
    const diff = getDateDiffInYMD(startDate, endDate);

    console.log(diff); // { years: 1, months: 2, days: 26 }

</script>
</body>
</html>

Output:

JavaScript difference between two dates in years months days

Comment if you have any doubts or suggestions on this Js date topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Tags:

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading