Search code examples
javascriptdayjs

dayjs - Calculate difference between hours and return it in minutes


Given two time parameters like: "13:00" and "00:00" How can I calculate the difference backwards and return it in minutes? My expected result is 780. Parameters can be 13:30. 13:45 etc.

API doc did not help, https://day.js.org/docs/en/display/difference, everybody is calculating date difference, not hours.

Thanks!


Solution

  • You don't need a library to do this.

    You can split the strings by a colon, then use the Date constructor to parse the hour and minutes. You can then subtract the two Dates to get the millisecond difference, and divide by 60000 to get the number of minutes:

    const a = "00:00";
    const b = "13:00"
    
    
    
    function calcDiff(start, end) {
      const [startHour, startMinutes] = start.split(":")
      const [endHour, endMinutes] = end.split(":")
    
      const diff = (new Date(null, null, null, endHour, endMinutes) - new Date(null, null, null, startHour, startMinutes)) / 60000
      return diff;
    }
    
    console.log(calcDiff(a, b))