Clock Difference - Angular 2

How can I get the difference between the hours between two dates in angular2? I do not want to use external type libraries moment.js.

Having, for example: eventTime = '2017-03-05 11:26:16 AM' and creationTime = '2017-03-06 12:26:16 AM'

let time = +params.data.incidentTime - +params.data.creationTime;  
console.log("time: " + time);

He should be back 25 hours, but he is returning NaN.

+6
source share
3 answers

This should do the job:

const date1 = params.data.incidentTime;
const date2 = params.data.creationTime;

const diffInMs = Date.parse(date2) - Date.parse(date1);
const diffInHours = diffInMs / 1000 / 60 / 60;

console.log(diffInHours);

Use Math.floorto round the result, or Math.ceilto round it.

+9
source

parse date type parameters on javascript Date .

let date1 = new Date(params.data.incidentTime).getTime();
let date2 = new Date(params.data.creationTime).getTime();
let time = date1 - date2;  //msec
let hoursDiff = time / (3600 * 1000);
+1
source

: -

let time:any = new Date("2017-03-05 11:26:16").getHours();
let date2:any = new Date("2017-03-06 12:26:16").getHours();
console.log(time -date2, time, date2, "sdfsd");

NaN

this is due to the fact that you use the character +before the date, which converts the date of the date to the number format, so it returns NAN (not a number)

-1
source

Source: https://habr.com/ru/post/1671584/


All Articles