Calculate the time between 2 Dates in TypeScript

avatar
Borislav Hadzhiev

Last updated: Feb 28, 2024
4 min

banner

# Table of Contents

  1. Calculate the time between 2 Dates in TypeScript
  2. Get the difference between 2 Dates in Days using TypeScript

If you need to get the difference between 2 Dates in Days, click on the second subheading.

# Calculate the time between 2 Dates in TypeScript

To calculate the time between 2 dates in TypeScript:

  1. Call the getTime() method on both dates.
  2. Subtract the first result from the second.
  3. The getTime() method returns a number representing the milliseconds between the Unix epoch and the given date.
index.ts
const date1 = new Date('2024-09-24'); const date2 = new Date('2024-09-25'); const msBetweenDates = date2.getTime() - date1.getTime(); console.log(msBetweenDates); // ๐Ÿ‘‰๏ธ 86400000

calculate time between 2 dates in typescript

The code for this article is available on GitHub

We used the getTime method to convert the dates to a Unix timestamp.

The result of the subtraction is the number of milliseconds between the two dates.

You can easily convert the milliseconds to any other unit.

# Format the result into hours, minutes and seconds

Here is an example that converts the difference between the dates (milliseconds) to time, formatted as hh:mm:ss.

index.ts
function padTo2Digits(num: number) { return num.toString().padStart(2, '0'); } function convertMsToTime(milliseconds: number) { let seconds = Math.floor(milliseconds / 1000); let minutes = Math.floor(seconds / 60); const hours = Math.floor(minutes / 60); seconds = seconds % 60; minutes = minutes % 60; // ๐Ÿ‘‡๏ธ If you want to roll hours over, e.g. 00 to 24 // ๐Ÿ‘‡๏ธ uncomment the line below // uncommenting next line gets you `00:00:00` instead of `24:00:00` // or `12:15:31` instead of `36:15:31`, etc. // ๐Ÿ‘‡๏ธ (roll hours over) // hours = hours % 24; return `${padTo2Digits(hours)}:${padTo2Digits(minutes)}:${padTo2Digits( seconds, )}`; } console.log(convertMsToTime(54000000)); // ๐Ÿ‘‰๏ธ 15:00:00 (15 hours) console.log(convertMsToTime(86400000)); // ๐Ÿ‘‰๏ธ 24:00:00 (24 hours) console.log(convertMsToTime(36900000)); // ๐Ÿ‘‰๏ธ 10:15:00 (10 hours, 15 minutes) console.log(convertMsToTime(15305000)); // ๐Ÿ‘‰๏ธ 04:15:05 (4 hours, 15 minutes, 5 seconds)

format result to hours minutes and seconds

The code for this article is available on GitHub

The function takes milliseconds as a parameter and returns the hours, minutes and seconds representation formatted as hh:mm:ss.

The padTo2Digits function takes care of adding a leading zero if the hours, minutes or seconds only contain a single digit (are less than 10).
index.js
function padTo2Digits(num) { return num.toString().padStart(2, '0'); } console.log(padTo2Digits(3)); // ๐Ÿ‘‰๏ธ '03' console.log(padTo2Digits(6)); // ๐Ÿ‘‰๏ธ '06' console.log(padTo2Digits(10)); // ๐Ÿ‘‰๏ธ '10'

We want to make sure the result doesn't alternate between single and double digit values depending on the hour, minutes and seconds.

In our convertMsToTime function, we:

  1. Converted the milliseconds to seconds by dividing the value by 1000.
  2. Converted the seconds to minutes by dividing the value by 60.
  3. Converted the minutes to hours by dividing the value by 60.
  4. (Optionally) - you can use the modulo (%) operator to reset the values to 0. If, for example, the user passed 86400000 as the milliseconds, which is equivalent to 24 hours.

You can uncomment the hours = hours % 24 line to roll the hours over.

The last step is to format the values for the hours, minutes and seconds in a way that suits your use case.

We formatted them as hh:mm:ss in the example, by adding a leading zero if the values are less than 10.

However, you can tweak the return value of the function depending on your use case.

Want to learn more about working with Dates in TypeScript? Check out these resources: Convert a String to a Date object in TypeScript,How to compare Dates in JavaScript and TypeScript.

# Get the difference between 2 Dates in Days using TypeScript

To calculate the number of days between 2 dates:

  1. Get the number of milliseconds between the Unix epoch and the Dates.
  2. Subtract the milliseconds of the start date from the milliseconds of the end date.
  3. Divide the result by the number of milliseconds in a day.
index.ts
function getDayDiff(startDate: Date, endDate: Date): number { const msInDay = 24 * 60 * 60 * 1000; return Math.round( Math.abs(Number(endDate) - Number(startDate)) / msInDay ); } // ๐Ÿ‘‡๏ธ 10 console.log( getDayDiff( new Date('2024-03-17'), new Date('2024-03-27') ) ); // ๐Ÿ‘‡๏ธ 30 console.log( getDayDiff( new Date('2024-04-17'), new Date('2024-05-17') ) );

get difference between 2 dates in days in typescript

The code for this article is available on GitHub

The getDayDiff function takes 2 Date objects as parameters and returns the difference in days between the two dates.

The msInDay variable stores the number of milliseconds there are in a day.

When you convert a Date object to a number, you get back a timestamp that represents the milliseconds elapsed between January 1st, 1970 and the given date.

# Calculate the number of Days between 2 Dates using getTime()

We could have called the getTime() method on both Date objects to achieve the same result.

index.ts
function getDayDiff(startDate: Date, endDate: Date): number { const msInDay = 24 * 60 * 60 * 1000; // ๐Ÿ‘‡๏ธ explicitly calling getTime() return Math.round( Math.abs(endDate.getTime() - startDate.getTime()) / msInDay, ); } // ๐Ÿ‘‡๏ธ 10 console.log( getDayDiff( new Date('2022-03-17'), new Date('2022-03-27') ) ); // ๐Ÿ‘‡๏ธ 30 console.log( getDayDiff( new Date('2022-04-17'), new Date('2022-05-17') ) );
The code for this article is available on GitHub

We used the getTime() method to explicitly convert the Date object to timestamp when subtracting.

The next step is to divide the result by the number of milliseconds in a day to convert the value from milliseconds to days.

We used the Math.abs() method to handle a scenario where we subtract a greater timestamp from a smaller one.

The Math.abs() method returns the absolute value of a number.

In other words, if the number is positive, the number is returned and if the number is negative, the negation of the number is returned.

index.js
console.log(Math.abs(-5)); // ๐Ÿ‘‰๏ธ 5 console.log(Math.abs(5)); // ๐Ÿ‘‰๏ธ 5

We passed the value to the Math.round() method to round to the nearest integer to deal with Daylight saving time.

Here are some examples of how the Math.round() method works.

index.js
console.log(Math.round(2.49)); // ๐Ÿ‘‰๏ธ 2 console.log(Math.round(2.5)); // ๐Ÿ‘‰๏ธ 3

The method rounds the number up or down to the nearest integer.

If the number is positive and its fractional part is greater than or equal to 0.5, it gets rounded to the next higher absolute value.

If the number is positive and its fractional portion is less than 0.5, it gets rounded to the lower absolute value.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev