简体   繁体   中英

How can I get the difference between two dates in hours, omitting the hours on weekends?

I need a function to check how many hours have passed between two dates, but if for example there is a weekend in between, then skip those hours.

Date 1: moment('2022-05-27 20:00:00).tz('UTC')

Date 2: moment('2022-05-30 20:00:00).tz('UTC')

Expected output: 24 hours

I get 25 if I do i <= n and 24 when I do i < n

But I do not use moment

Note that this should work across daylight savings changes in the locale you are in

 const d1 = new Date('2022-05-27 20:00:00') const d2 = new Date('2022-05-30 20:00:00') console.log(d1, d2) let hours = 0; for (let i = d1.getTime(), n = d2.getTime(); i < n; i += 3600000) { const d = new Date(i); if (![0, 6].includes(d.getDay())) hours++; } console.log(hours)

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