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