简体   繁体   English

如何以小时为单位计算两个日期之间的差异,省略周末的时间?

[英]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')日期1: moment('2022-05-27 20:00:00).tz('UTC')

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

Expected output: 24 hours预期输出: 24 hours

I get 25 if I do i <= n and 24 when I do i < n如果我做i <= n ,我得到 25,当我做 i i < n n 时,我得到 24

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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