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(\
// 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();
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()
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
.
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();