Learn how to calculate the difference between two dates in years, months, and days using JavaScript. You can follow the steps below:
- Create two date objects using the Date() constructor.
- Calculate the difference between the two dates in milliseconds using the getTime() method.
- Convert the difference to days using division by the number of milliseconds in a day (1000 * 60 * 60 * 24).
- Calculate the number of years by dividing the number of days by 365 (or 366 for leap years).
- Calculate the number of months by dividing the number of days by 30.44 (the average number of days in a month).
- 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:
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