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.
To calculate the number of hours between two dates we can simply subtract the two values and multiply by 24.
To calculate the time between 2 dates in TypeScript, call the getTime() method on both dates when subtracting, e.g. date2. getTime() - date1. getTime() .
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
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With