用js实现倒数日的代码
时间: 2024-02-13 12:02:36 浏览: 23
以下是用 JavaScript 实现倒数日的代码:
```javascript
// 目标日期(示例为2022年元旦)
const targetDate = new Date("2022-01-01T00:00:00");
// 获取倒数日信息的函数
function getCountdown() {
// 当前日期
const currentDate = new Date();
// 计算时间差(单位:毫秒)
const timeDiff = targetDate.getTime() - currentDate.getTime();
// 判断是否已过期
if (timeDiff < 0) {
return "已过期";
}
// 计算剩余天数、小时数、分钟数、秒数
const days = Math.floor(timeDiff / (24 * 60 * 60 * 1000));
const hours = Math.floor((timeDiff / (60 * 60 * 1000)) % 24);
const minutes = Math.floor((timeDiff / (60 * 1000)) % 60);
const seconds = Math.floor((timeDiff / 1000) % 60);
// 返回倒数日信息
return `${days}天${hours}小时${minutes}分钟${seconds}秒`;
}
// 每隔1秒更新一次倒数日信息
setInterval(() => {
const countdown = getCountdown();
console.log(countdown);
}, 1000);
```
该代码通过 `getCountdown` 函数计算目标日期与当前日期的时间差,进而计算出剩余天数、小时数、分钟数、秒数。然后通过 `setInterval` 函数每隔1秒更新一次倒数日信息。你可以将目标日期修改为任何你想要的日期。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.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)
![](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)