Typescript : find date difference in dates/hours/minutes

11,780

Solution 1

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

Solution 2

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

Solution 3

Well, there are pure javascript way of doing it like in Check time difference in Javascript

or you can reuse the efforts put in by engineers who delevloped moment.js. In moment.js, there is a concept called duration whose link is - https://momentjs.com/docs/#/durations/ and you can even find the difference in duration by referencing docs here - https://momentjs.com/docs/#/durations/diffing/

Share:
11,780
George George
Author by

George George

Updated on June 25, 2022

Comments

  • George George
    George George almost 2 years

    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

  • George George
    George George over 5 years
    thank you for the reply. I did this approach but then I face "getTime() is not a function"..
  • veben
    veben over 5 years
    You can try to look at this article: expertcodeblog.wordpress.com/2017/12/12/…