Sling Academy
Home/JavaScript/How to Subtract and Compare 2 Dates in JavaScript

How to Subtract and Compare 2 Dates in JavaScript

Last updated: February 19, 2023

This article is about subtracting and comparing 2 dates in Javascript. We’ll have a look at the fundamentals and then walk through several examples of applying that knowledge in practice.

Overview

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.

Fortunately, Javascript allows us to subtract 2 date objects directly, like this:

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.

Examples

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);

Output:

37

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);

Output:

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

If you want to subtract 2 dates belonging to 2 different timezones, construct date objects with date strings containing timezone information. Then we can subtract 2 like the examples above. Javascript will take care of the calculations for us.

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); 

Output:

19

Next Article: JavaScript: Convert timestamp to date time and vice versa

Previous Article: JavaScript: 3 ways to check if a date string is valid

Series: Date and Time in JavaScript: Basic to Advanced Tutorials

JavaScript

You May Also Like

  • Handle Zoom and Scroll with the Visual Viewport API in JavaScript
  • Improve Security Posture Using JavaScript Trusted Types
  • Allow Seamless Device Switching Using JavaScript Remote Playback
  • Update Content Proactively with the JavaScript Push API
  • Simplify Tooltip and Dropdown Creation via JavaScript Popover API
  • Improve User Experience Through Performance Metrics in JavaScript
  • Coordinate Workers Using Channel Messaging in JavaScript
  • Exchange Data Between Iframes Using Channel Messaging in JavaScript
  • Manipulating Time Zones in JavaScript Without Libraries
  • Solving Simple Algebraic Equations Using JavaScript Math Functions
  • Emulating Traditional OOP Constructs with JavaScript Classes
  • Smoothing Out User Flows: Focus Management Techniques in JavaScript
  • Creating Dynamic Timers and Counters with JavaScript
  • Implement Old-School Data Fetching Using JavaScript XMLHttpRequest
  • Load Dynamic Content Without Reloading via XMLHttpRequest in JavaScript
  • Manage Error Handling and Timeouts Using XMLHttpRequest in JavaScript
  • Handle XML and JSON Responses via JavaScript XMLHttpRequest
  • Make AJAX Requests with XMLHttpRequest in JavaScript
  • Customize Subtitle Styling Using JavaScript WebVTT Integration