简体   繁体   中英

How to calculate time difference in 24 hour format across midnight

I am calculating time difference between two time in 24 hour format. Here I have a case where start time is 22 which is 10 pm and end time is 6 which is 6 am of another day. I am trying if initial time is greater than end time than (24 - start time)+ end Time. But how exactly do this in the case of time like hh:mm by ignoring seconds.

Like this

Hours

 const diff = (s, e) => s > e ? Math.abs(s - 24 - e) : e - s; console.log(diff(22, 6)) console.log(diff(6, 22))

HH:MM

 const pad = num => ("0" + num).slice(-2); const diff = (s, e) => { const [shh, smm] = s.split(":"); const [ehh, emm] = e.split(":"); const smin = +smm + (60 * shh); const emin = +emm + (60 * ehh); let mDiff = s > e ? Math.abs(smin - (24 * 60) - emin) : emin - smin; let hours = Math.floor(mDiff / 60); let minutes = mDiff % 60; return pad(hours) + ":" + pad(minutes) } console.log(diff("22:03", "06:04")) console.log(diff("06:04", "22:03"))

Use moment library.

Something like

moment().subtract(1,'days').startOf('day').toString()

moment().subtract(1,'days').endOf('day').toString()

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