[date] How can I calculate the time between 2 Dates in typescript

This works in Javascript

new Date()-new Date("2013-02-20T12:01:04.753Z")

But in typescript I can't rest two new Dates

Date("2013-02-20T12:01:04.753Z")

Don't work because paremater not match date signature

This question is related to date typescript

The answer is


It doesn't work because Date - Date relies on exactly the kind of type coercion TypeScript is designed to prevent.

There is a workaround this using the + prefix:

var t = Date.now() - +(new Date("2013-02-20T12:01:04.753Z");

Or, if you prefer not to use Date.now():

var t = +(new Date()) - +(new Date("2013-02-20T12:01:04.753Z"));

See discussion here.

Or see Siddharth Singh's answer, below, for a more elegant solution using valueOf()


Use the getTime method to get the time in total milliseconds since 1970-01-01, and subtract those:

var time = new Date().getTime() - new Date("2013-02-20T12:01:04.753Z").getTime();

In order to calculate the difference you have to put the + operator,

that way typescript converts the dates to numbers.

+new Date()- +new Date("2013-02-20T12:01:04.753Z")

From there you can make a formula to convert the difference to minutes or hours.


// TypeScript

const today = new Date();
const firstDayOfYear = new Date(today.getFullYear(), 0, 1);

// Explicitly convert Date to Number
const pastDaysOfYear = ( Number(today) - Number(firstDayOfYear) );

This is how it should be done in typescript:

(new Date()).valueOf() - (new Date("2013-02-20T12:01:04.753Z")).valueOf()

Better readability:

      var eventStartTime = new Date(event.startTime);
      var eventEndTime = new Date(event.endTime);
      var duration = eventEndTime.valueOf() - eventStartTime.valueOf();