Skip to content

JavaScript difference between two dates in days hours and minutes

  • by

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.

  1. Create two date objects using the Date() constructor.
  2. Calculate the difference between the two dates in milliseconds using the getTime() method.
  3. Calculate the total number of minutes by dividing the difference by 1000 milliseconds per second, 60 seconds per minute.
  4. Calculate the total number of hours by dividing the total number of minutes by 60.
  5. Calculate the total number of days by dividing the total number of hours by 24.
  6. 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:

JavaScript difference between two dates in days hours and minutes

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