Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript : find date difference in dates/hours/minutes

I am working on a date comparison and I am trying to calculate and display the difference between two dates in a format of dates, hours, minutes... Date values are stored in the DB like:

EndDate : 2018-11-29 10:49:49.9396033
PurchaseDate: 2018-11-29 10:49:07.4154497

And in my Angular component, I have:

let result = new Date(res.endDate).valueOf() - new Date(res.purchaseDate).valueOf();

This leads to: 42524 which I am not sure what it represents.

I wonder what is the proper way to calculate the time difference between two dates and also how can I display the result in a proper and readable way.

Any help is welcome

like image 625
George George Avatar asked Nov 29 '18 12:11

George George


2 Answers

Working Example in codepen

 let endDate = new Date("2018-11-29 10:49:07.4154497");
 let purchaseDate = new Date("2018-11-29 10:49:49.9396033");
 let diffMs = (purchaseDate - endDate); // milliseconds
 let diffDays = Math.floor(diffMs / 86400000); // days
 let diffHrs = Math.floor((diffMs % 86400000) / 3600000); // hours
 let diffMins = Math.round(((diffMs % 86400000) % 3600000) / 60000); // minutes
 console.log(diffDays + " days, " + diffHrs + " hours, " + diffMins + " 
 minutes");
like image 152
Anas Rezk Avatar answered Sep 30 '22 06:09

Anas Rezk


You can use the getTime() method to get the difference time in milliseconds

let time = purchaseDate.getTime() - endDate.getTime();

You can then format the date as you want with the DatePipe librairy : https://angular.io/api/common/DatePipe

like image 38
veben Avatar answered Sep 30 '22 05:09

veben