Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Date difference in hours - Angular 2

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.

like image 320
user630209 Avatar asked Mar 06 '17 09:03

user630209


People also ask

How do you find the difference between two dates in hours?

To calculate the number of hours between two dates we can simply subtract the two values and multiply by 24.

How do I calculate hours between two dates TypeScript?

To calculate the time between 2 dates in TypeScript, call the getTime() method on both dates when subtracting, e.g. date2. getTime() - date1. getTime() .


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

like image 163
seidme Avatar answered Sep 25 '22 21:09

seidme


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);
like image 25
Babar Bilal Avatar answered Sep 25 '22 21:09

Babar Bilal