Last updated: Feb 28, 2024
Reading timeยท4 min
If you need to get the difference between 2 Dates in Days, click on the second subheading.
To calculate the time between 2 dates in TypeScript:
getTime()
method on both dates.getTime()
method returns a number representing the milliseconds between
the Unix epoch and the given date.const date1 = new Date('2024-09-24'); const date2 = new Date('2024-09-25'); const msBetweenDates = date2.getTime() - date1.getTime(); console.log(msBetweenDates); // ๐๏ธ 86400000
We used the getTime method to convert the dates to a Unix timestamp.
You can easily convert the milliseconds to any other unit.
Here is an example that converts the difference between the dates (milliseconds)
to time, formatted as hh:mm:ss
.
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)
The function takes milliseconds as a parameter and returns the hours, minutes
and seconds representation formatted as hh:mm:ss
.
padTo2Digits
function takes care of adding a leading zero if the hours, minutes or seconds only contain a single digit (are less than 10
).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:
1000
.60
.60
.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.
To calculate the number of days between 2 dates:
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') ) );
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.
Date
object to a number
, you get back a timestamp that represents the milliseconds elapsed between January 1st, 1970 and the given date.We could have called the getTime()
method on both Date
objects to achieve
the same result.
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') ) );
We used the getTime()
method to explicitly convert the Date
object to
timestamp when subtracting.
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.
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.
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.
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.
You can learn more about the related topics by checking out the following tutorials: