js 获取时间从昨天的0点开始 到23点59分59秒 且时分秒补0
时间: 2024-02-20 17:56:25 浏览: 34
可以使用 JavaScript 中的 Date 对象和字符串格式化函数来实现。
以下是示例代码:
```
// 获取当前时间的 Date 对象
let now = new Date();
// 将时间设置为昨天的0点
now.setDate(now.getDate() - 1);
now.setHours(0, 0, 0, 0);
// 获取昨天的23点59分59秒
let end = new Date(now.getTime() + 24 * 60 * 60 * 1000 - 1);
end.setHours(23, 59, 59, 0);
// 格式化时间为字符串,补0到两位
function formatTime(num) {
return num < 10 ? '0' + num : num;
}
let startTimeStr = `${now.getFullYear()}-${formatTime(now.getMonth() + 1)}-${formatTime(now.getDate())} 00:00:00`;
let endTimeStr = `${end.getFullYear()}-${formatTime(end.getMonth() + 1)}-${formatTime(end.getDate())} ${formatTime(end.getHours())}:${formatTime(end.getMinutes())}:${formatTime(end.getSeconds())}`;
console.log(startTimeStr); // 输出昨天0点的时间字符串
console.log(endTimeStr); // 输出昨天23点59分59秒的时间字符串
```
这段代码会输出昨天0点和23点59分59秒的时间字符串,格式为 `yyyy-mm-dd hh:mm:ss`,时、分、秒部分会自动补0。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.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)