Sometimes, we want to calculate the time between 2 Dates in TypeScript.
In this article, we’ll look at how to calculate the time between 2 Dates in TypeScript.
How to calculate the time between 2 Dates in TypeScript?
To calculate the time between 2 Dates in TypeScript, we can subtract the timestamps returned by the Date
instances.
For instance, we write
const eventStartTime = new Date(event.startTime);
const eventEndTime = new Date(event.endTime);
const duration = eventEndTime.valueOf() - eventStartTime.valueOf();
to get the timestamps in milliseconds with valueOf
.
Then we subtract them to get their differences in milliiseconds.
We create the dates with the Date
constructor.
Conclusion
To calculate the time between 2 Dates in TypeScript, we can subtract the timestamps returned by the Date
instances.