Open In App

How to Calculate the Time Between 2 Dates in TypeScript ?

Last Updated : 21 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will calculate the time between two different dates using TypeScript. We will use the getTime() method to get the current time of the specified date.

Syntax:

const variable_name = new Date();
const time = variable_name.getTime();

Note: The getTime() method will return the time in the milliseconds.

Approach

  • Create two different dates using the Date object in TypeScript.
  • Now, use the getTime() method on the created dates to get the time in milliseconds.
  • After getting the time, subtract them to get the difference between them.
  • Now, convert the resulting millisecond time into hours and minutes using formulas.

Example 1: The below example will explain the use of the getTime() method to calculate the time between two dates.

Javascript




// Future Date
const firstDate: Date = new Date('2023-12-21');
 
// Current Date
const secondDate: Date = new Date();
 
// Time Difference in Milliseconds
const milliDiff: number = firstDate.getTime()
    - secondDate.getTime();
 
// Converting time into hh:mm:ss format
 
// Total number of seconds in the difference
const totalSeconds = Math.floor(milliDiff / 1000);
 
// Total number of minutes in the difference
const totalMinutes = Math.floor(totalSeconds / 60);
 
// Total number of hours in the difference
const totalHours = Math.floor(totalMinutes / 60);
 
// Getting the number of seconds left in one minute
const remSeconds = totalSeconds % 60;
 
// Getting the number of minutes left in one hour
const remMinutes = totalMinutes % 60;
 
console.log(`${totalHours}:${remMinutes}:${remSeconds}`);


Output:

14:19:59

Example 2: The below example will show you the difference just like countdown using the setInterval() method.

Javascript




const countDown = () => {
 
    // Future Date
    const firstDate: Date = new Date('2023-12-21');
     
    // Current Date
    const secondDate: Date = new Date();
 
    // Time Difference in Milliseconds
    const milliDiff: number = firstDate.getTime()
        - secondDate.getTime();
 
    // Converting time into hh:mm:ss format
 
    // Total number of seconds in the difference
    const totalSeconds = Math.floor(milliDiff / 1000);
 
    // Total number of minutes in the difference
    const totalMinutes = Math.floor(totalSeconds / 60);
 
    // Total number of hours in the difference
    const totalHours = Math.floor(totalMinutes / 60);
 
    // Getting the number of seconds left in one minute
    const remSeconds = totalSeconds % 60;
 
    // Getting the number of minutes left in one hour
    const remMinutes = totalMinutes % 60;
 
    console.log(`${totalHours}:${remMinutes}:${remSeconds}`);
}
 
setInterval(countDown, 1000);


Output:

dateDiffGIF



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads