Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to calculate the difference between two dates in JavaScript?
To calculate the difference between two dates in JavaScript, use the getTime() method to get timestamps in milliseconds, then subtract one from the other.
Basic Date Difference Calculation
The getTime() method returns the number of milliseconds since January 1, 1970. By subtracting two timestamps, you get the difference in milliseconds.
<!DOCTYPE html>
<html>
<body>
<script>
var dateFirst = new Date("11/25/2017");
var dateSecond = new Date("11/28/2017");
// time difference in milliseconds
var timeDiff = Math.abs(dateSecond.getTime() - dateFirst.getTime());
// days difference
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
// display result
console.log("Difference: " + diffDays + " days");
alert("Difference: " + diffDays + " days");
</script>
</body>
</html>
Difference: 3 days
Different Time Units
You can convert the millisecond difference to various time units:
<!DOCTYPE html>
<html>
<body>
<script>
var start = new Date("2023-01-01 10:00:00");
var end = new Date("2023-01-02 14:30:00");
var timeDiff = Math.abs(end.getTime() - start.getTime());
var diffSeconds = Math.floor(timeDiff / 1000);
var diffMinutes = Math.floor(timeDiff / (1000 * 60));
var diffHours = Math.floor(timeDiff / (1000 * 60 * 60));
var diffDays = Math.floor(timeDiff / (1000 * 60 * 60 * 24));
console.log("Seconds: " + diffSeconds);
console.log("Minutes: " + diffMinutes);
console.log("Hours: " + diffHours);
console.log("Days: " + diffDays);
</script>
</body>
</html>
Seconds: 103800 Minutes: 1730 Hours: 28 Days: 1
Calculating Age
A common use case is calculating someone's age:
<!DOCTYPE html>
<html>
<body>
<script>
var birthDate = new Date("1990-05-15");
var today = new Date();
var timeDiff = today.getTime() - birthDate.getTime();
var ageInYears = Math.floor(timeDiff / (1000 * 3600 * 24 * 365.25));
console.log("Age: " + ageInYears + " years");
</script>
</body>
</html>
Time Conversion Constants
| Unit | Milliseconds | Formula |
|---|---|---|
| Second | 1,000 | 1000 |
| Minute | 60,000 | 1000 * 60 |
| Hour | 3,600,000 | 1000 * 60 * 60 |
| Day | 86,400,000 | 1000 * 60 * 60 * 24 |
Key Points
- Use
Math.abs()to get absolute difference (always positive) - Use
Math.floor()for complete units,Math.ceil()to round up - Be careful with leap years when calculating years
-
getTime()returns milliseconds since Unix epoch
Conclusion
Date difference calculation in JavaScript involves getting timestamps with getTime() and dividing by appropriate conversion factors. This method works reliably for calculating days, hours, minutes, or any time unit difference.
Advertisements
