简体   繁体   中英

Calculate the difference between two dates and give the result in hh:mm format

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

How could I found the time difference?

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()}`
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((secs%3600) / 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM