Skip to main content

How to calculate the time difference (days, hours, minutes) between two dates in JavaScript

In this tutorial, I will guide you on how to write a function that calculates the time difference between two JavaScript Date objects and return the calculation of the difference in days, hours, and minutes.
You can get the javascript difference between date objects by subtracting the date Objects. It will return the difference in milliseconds.
const diffInMilliseconds = Math.abs(new Date('2019/10/1 00:00:00') - new Date('2019/10/2 00:00:00'));

console.log(diffInMilliseconds); //86400000
In the above example, I have subtracted two date objects which returns the milliseconds. Math.abs is used to get positive numbers. The above example return 86500000 (milliseconds) which is exactly 1 day.

Calculate Time Difference between two dates in JavaScript

function timeDiffCalc(dateFuture, dateNow) {
    let diffInMilliSeconds = Math.abs(dateFuture - dateNow) / 1000;

    // calculate days
    const days = Math.floor(diffInMilliSeconds / 86400);
    diffInMilliSeconds -= days * 86400;
    console.log('calculated days', days);

    // calculate hours
    const hours = Math.floor(diffInMilliSeconds / 3600) % 24;
    diffInMilliSeconds -= hours * 3600;
    console.log('calculated hours', hours);

    // calculate minutes
    const minutes = Math.floor(diffInMilliSeconds / 60) % 60;
    diffInMilliSeconds -= minutes * 60;
    console.log('minutes', minutes);

    let difference = '';
    if (days > 0) {
      difference += (days === 1) ? `${days} day, ` : `${days} days, `;
    }

    difference += (hours === 0 || hours === 1) ? `${hours} hour, ` : `${hours} hours, `;

    difference += (minutes === 0 || hours === 1) ? `${minutes} minutes` : `${minutes} minutes`; 

    return difference;
  }

  console.log(timeDiffCalc(new Date('2019/10/1 04:10:00'), new Date('2019/10/2 18:20:00')));

// the time difference is:
// 1 day, 14 hours, 10 minutes
The above function will work perfectly to calculate the time difference (except daylight saving) between two dates.
The first line of the function is to get the time difference in milliseconds by subtracting two Date objects. From that milliseconds, we can calculate days, hours, and minutes. I will explain it step by step below.

Calculate The Number of Days Between Two Dates in JavaScript

// calculate (and subtract) whole days
const days = Math.floor(diffInMilliSeconds / 86400);
diffInMilliSeconds -= days * 86400;
console.log('calculated days', days);
To calculate the number of days difference between two objects, we should divide the diffInMilliSeconds (time difference in milliseconds) with 86400 (which is the number of seconds per day).
After that, we should subtract the days in diffInMilliSeconds with the number of days in milliseconds (days * 86400) for further accurate calculation of hours and minutes.

Calculate Hours Difference between Two Dates in JavaScript

// calculate hours
const hours = Math.floor(diffInMilliSeconds / 3600) % 24;
diffInMilliSeconds -= hours * 3600;
console.log('calculated hours', hours);
To calculate the hours difference of the two dates, we should divide the diffInMilliSeconds with 3600 which is the milliseconds of 1 hour, and then further divide it by 24 (24 hours per day) and get the remainder using modules operator. After that, subtract the diffInMilliSeconds with the number of hours in milliseconds (hours * 3600) for further calculation of minutes.

Calculate Minutes Difference between Two Date in JavaScript

// calculate minutes
const minutes = Math.floor(diffInMilliSeconds / 60) % 60;
diffInMilliSeconds -= minutes * 60;
console.log('minutes', minutes);
To calculate the minutes difference between two dates, we should divide the diffInMilliSecondswith 60 seconds) and then get the remainder by dividing it by 60 (60 minutes per hour). After that, subtract the diffInMilliSeconds with the number of minutes in milliseconds (minutes * 60).

Conclusion

I hope, you have learned to play with the Date to calculate the time difference in JavaScript. The above method will work for most of the situations. If you have to manage the daylight saving in your calculation this method is not recommended. I highly recommend you to use countdown.js for overcoming the daylight saving issue. Thank you.

Comments

Popular posts from this blog

4 Ways to Communicate Across Browser Tabs in Realtime

1. Local Storage Events You might have already used LocalStorage, which is accessible across Tabs within the same application origin. But do you know that it also supports events? You can use this feature to communicate across Browser Tabs, where other Tabs will receive the event once the storage is updated. For example, let’s say in one Tab, we execute the following JavaScript code. window.localStorage.setItem("loggedIn", "true"); The other Tabs which listen to the event will receive it, as shown below. window.addEventListener('storage', (event) => { if (event.storageArea != localStorage) return; if (event.key === 'loggedIn') { // Do something with event.newValue } }); 2. Broadcast Channel API The Broadcast Channel API allows communication between Tabs, Windows, Frames, Iframes, and  Web Workers . One Tab can create and post to a channel as follows. const channel = new BroadcastChannel('app-data'); channel.postMessage(data); And oth...

Certbot SSL configuration in ubuntu

  Introduction Let’s Encrypt is a Certificate Authority (CA) that provides an easy way to obtain and install free  TLS/SSL certificates , thereby enabling encrypted HTTPS on web servers. It simplifies the process by providing a software client, Certbot, that attempts to automate most (if not all) of the required steps. Currently, the entire process of obtaining and installing a certificate is fully automated on both Apache and Nginx. In this tutorial, you will use Certbot to obtain a free SSL certificate for Apache on Ubuntu 18.04 and set up your certificate to renew automatically. This tutorial will use a separate Apache virtual host file instead of the default configuration file.  We recommend  creating new Apache virtual host files for each domain because it helps to avoid common mistakes and maintains the default files as a fallback configuration. Prerequisites To follow this tutorial, you will need: One Ubuntu 18.04 server set up by following this  initial ...

Working with Node.js streams

  Introduction Streams are one of the major features that most Node.js applications rely on, especially when handling HTTP requests, reading/writing files, and making socket communications. Streams are very predictable since we can always expect data, error, and end events when using streams. This article will teach Node developers how to use streams to efficiently handle large amounts of data. This is a typical real-world challenge faced by Node developers when they have to deal with a large data source, and it may not be feasible to process this data all at once. This article will cover the following topics: Types of streams When to adopt Node.js streams Batching Composing streams in Node.js Transforming data with transform streams Piping streams Error handling Node.js streams Types of streams The following are four main types of streams in Node.js: Readable streams: The readable stream is responsible for reading data from a source file Writable streams: The writable stream is re...