There are many scenarios where you may need to subtract 2 dates. For example, you want to calculate the duration of a task, the exact age of a person, the difference between 2 dates for a booking system (hotel, air ticket, etc.), or the time left until a certain event in the future.
const result = date1 - date2;
result will be the number of milliseconds. If result is a negative number, then date1 is earlier than date2 and vice versa.
To convert result to hours, divide it by 1000 * 60 * 60:
hours = result / (1000 * 60 * 60)
In case you want to turn result into days, divide it by 1000 * 60 * 60 * 24:
days = result / (1000 * 60 * 60 * 24)
Now, let’s take a look at some practical examples to deeply understand all of this.
Calculating the Age of a Person
To calculate the age of a person, what we have to do is to get the current date and subtract the birthdate from it. Here’s the code:
const birthdate = new Date(1985, 11, 17); const today = new Date(); const diff = today - birthdate; const age = Math.floor(diff / (1000 * 60 * 60 * 24 * 365.25)); // we use 365.25 because the average year is 365.25 days long. Every 4 years, we add a day to account for leap years. console.log(age);
Calculating the Days Left Until an Event (Countdown)
To calculate the number of days left until an event, we can subtract the current date from the event date. Here’s the code:
const now = new Date(); const endOfYear = new Date('2023-12-31'); const days = Math.floor((endOfYear - now) / 1000 / 60 / 60 / 24); console.log('The number of days until the end of 2023 is:', days);
The number of days until the end of 2023 is: 358
When you run the code snippet above, it will return a different result. This makes sense because new Date() will give different values at different times.
Subtracting Two Dates in Two Different Timezones
This example calculates the time difference between 2 dates (one in UTC and the other in EST time):
// UTC const date1 = new Date('2023-01-02T00:00:00.000Z'); // Eastern Standard Time (EST). UTC-5 const date2 = new Date('2023-01-01T00:00:00.000-05:00'); const diff = date1 - date2; const diffInHours = diff / 1000 / 60 / 60; console.log(diffInHours);