用JS 24小时制 给定多个时间段 计算剩下的时间段
时间: 2024-03-12 07:49:47 浏览: 34
好的,我可以为您提供帮助。您可以将多个时间段表示为开始时间和结束时间的数组,然后使用JavaScript计算剩余时间。以下是一个示例代码:
```javascript
// 将时间段表示为开始时间和结束时间的数组
const timeSlots = [
{ start: "2021-08-01 08:00:00", end: "2021-08-01 10:30:00" },
{ start: "2021-08-01 12:00:00", end: "2021-08-01 14:30:00" },
{ start: "2021-08-01 15:00:00", end: "2021-08-01 16:00:00" }
];
// 将字符串格式的日期转换为日期对象
function parseDate(str) {
const [date, time] = str.split(" ");
const [year, month, day] = date.split("-");
const [hour, minute, second] = time.split(":");
return new Date(year, month - 1, day, hour, minute, second);
}
// 计算剩余时间
function calculateRemainingTime() {
let now = new Date();
let remainingTime = 0;
for (let slot of timeSlots) {
let start = parseDate(slot.start);
let end = parseDate(slot.end);
// 如果当前时间在时间段内,则跳过
if (now >= start && now <= end) {
now = end;
continue;
}
// 计算剩余时间
if (now < start) {
remainingTime += start - now;
}
remainingTime += end - start;
now = end;
}
return remainingTime;
}
// 将毫秒数转换为人类可读的时间格式
function formatTime(milliseconds) {
const totalSeconds = Math.floor(milliseconds / 1000);
const hours = Math.floor(totalSeconds / 3600);
const minutes = Math.floor((totalSeconds % 3600) / 60);
const seconds = totalSeconds % 60;
return `${hours}小时${minutes}分钟${seconds}秒`;
}
// 输出剩余时间
console.log(formatTime(calculateRemainingTime()));
```
您可以根据自己的需求修改时间段的数组,然后使用`calculateRemainingTime()`函数计算剩余时间,并使用`formatTime()`函数将毫秒数转换为人类可读的时间格式。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)