Date difference in hours - Angular 2

2020-02-06 08:13发布

问题:

How can I get difference in hours between two dates in angular2? I don't want to use external libs like moment.js.

Having, for example: incidentTime = '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);

It should return 25 hours, but It returns NaN.

回答1:

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.floor to round the result down, or Math.ceil to round it up



回答2:

parse the date type parameters to javascript's Date type.

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


回答3:

Try this:-

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

but It returns NaN

this is because you are using + sign before date which is converting youtr date into number format so returning NAN(not a number)