Skip to content

JavaScript difference between two dates

  • by

You can get difference between two dates by subtracting one date from another in JavaScript. This will give you the number of milliseconds between the two dates. You can then convert this value to the desired time unit (seconds, minutes, hours, days, etc.) using simple arithmetic.

JavaScript difference between two dates example

Simple example code calculate the difference between two dates in days:

<!DOCTYPE html>
<html>
<body>
<script>
    const date1 = new Date('2022-10-12');
    const date2 = new Date('2022-01-05');

    const diffInMs = Math.abs(date2 - date1);
    const diffInDays = Math.floor(diffInMs / (1000 * 60 * 60 * 24));

    console.log(diffInDays); 

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

Output:

JavaScript difference between two dates

How to calculate the number of days between two dates in JavaScript ?

Answer: Another method to calculate the number of days between two dates in JavaScript is to use the getTime() method to get the time value of each date, then calculate the difference in days by dividing the difference in time by the number of milliseconds in a day.

const date1 = new Date('2022-01-01');
const date2 = new Date('2022-01-05');

const timeDiff = date2.getTime() - date1.getTime();
const diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24)); 

console.log(diffDays); // Output: 4

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

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