How can I calculate the time between 2 Dates in typescript

DateTypescript

Date Problem Overview


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

Date Solutions


Solution 1 - Date

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();

Solution 2 - Date

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();

Solution 3 - Date

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.

Solution 4 - Date

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

There is a workaround for 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()

Solution 5 - Date

// TypeScript

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

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser2025288View Question on Stackoverflow
Solution 1 - DateGuffaView Answer on Stackoverflow
Solution 2 - DateSiddharth SinghView Answer on Stackoverflow
Solution 3 - DatealexalejandroemView Answer on Stackoverflow
Solution 4 - DateJude FisherView Answer on Stackoverflow
Solution 5 - DatealtergothenView Answer on Stackoverflow