Home > Back-end >  Calculate the difference between two dates and give the result in hh:mm format
Calculate the difference between two dates and give the result in hh:mm format

Time:12-31

date1=2023-01-02T12:22:00
date2=2023-01-03T22:15:00

How could I found the time difference?

CodePudding user response:

function secondsToHMS(secs) {
  function z(n){return (n<10?'0':'')   n;}
  var sign = secs < 0 ? '-' : '';
  secs = Math.abs(secs);
  return sign   z(secs/3600 |0)   ':'   z((secs600) / 60 |0);
}

var d1 = new Date('2023-01-03T22:15:00');
var d2 = new Date('2023-01-02T12:22:00');

//console.log( secondsToHMS((d1 - d2) / 1000)); // 33:53

CodePudding user response:

You can refer to the answer here: https://stackoverflow.com/a/12193371/9067107

The steps are firstly converting the UTC time via new Date() and calculate the different by date1 - date2 and get the Hours / Minutes different.

Lets assume you want to have HH:mm format in string

let date1 = new Date('2023-01-02T12:22:00')
let date2 = new Date('2023-01-03T22:15:00')
let diff = new Date(date2 - date1)
let diffInHoursMinutes = `${diff.getHours()}:${diff.getMinutes()}`
  • Related