Learn how to calculate the difference between two dates in days, hours, and minutes using JavaScript. This step-by-step guide will show you how to create date objects, calculate the difference in milliseconds, and then convert the result to the number of days, hours, and minutes.
- Create two date objects using the Date() constructor.
- Calculate the difference between the two dates in milliseconds using the getTime() method.
- Calculate the total number of minutes by dividing the difference by 1000 milliseconds per second, 60 seconds per minute.
- Calculate the total number of hours by dividing the total number of minutes by 60.
- Calculate the total number of days by dividing the total number of hours by 24.
- Calculate the remaining hours by subtracting the total number of days from the hours, and the remaining minutes by subtracting the total number of hours from the minutes.
Javascript difference between two dates in days hours and minutes examples
simple example code.
<!DOCTYPE html>
<html>
<body>
<script>
function getDateDiffInDHM(startDate, endDate) {
const diffMs = Math.abs(endDate.getTime() - startDate.getTime());
const totalMinutes = Math.floor(diffMs / (1000 * 60));
const days = Math.floor(totalMinutes / (24 * 60));
const hours = Math.floor((totalMinutes - (days * 24 * 60)) / 60);
const minutes = totalMinutes - (days * 24 * 60) - (hours * 60);
return { days, hours, minutes };
}
const startDate = new Date("2021-04-28T13:17:31.000Z")
const endDate = new Date("2021-04-20T22:08:07.000Z")
const diff = getDateDiffInDHM(startDate, endDate);
console.log(diff); // { days: 450, hours: 0, minutes: 0 }
</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