js怎么获取时间,并且跟着时间变动,格式是yy-mm-dd-hh-mm-ss
时间: 2023-07-22 22:20:32 浏览: 51
要获取当前时间并且跟着时间变动,并且格式为 `yy-mm-dd-hh-mm-ss`,可以使用JavaScript的setInterval函数来定时更新时间。以下是一个示例代码:
```
function updateTime() {
let currentTime = new Date();
let year = currentTime.getFullYear();
let month = currentTime.getMonth() + 1;
let day = currentTime.getDate();
let hours = currentTime.getHours();
let minutes = currentTime.getMinutes();
let seconds = currentTime.getSeconds();
// 格式化时间
if (month < 10) {
month = "0" + month;
}
if (day < 10) {
day = "0" + day;
}
if (hours < 10) {
hours = "0" + hours;
}
if (minutes < 10) {
minutes = "0" + minutes;
}
if (seconds < 10) {
seconds = "0" + seconds;
}
let formattedTime = year + "-" + month + "-" + day + "-" + hours + "-" + minutes + "-" + seconds;
// 在页面中显示时间
document.getElementById('clock').innerHTML = formattedTime;
}
// 每秒钟更新一次时间
setInterval(updateTime, 1000);
```
这个代码会在页面上显示当前时间,并且每秒钟更新一次。时间格式为 `yy-mm-dd-hh-mm-ss`。你需要在HTML文件中添加一个具有 `id="clock"` 的元素,以便在页面中显示时间。
相关推荐
![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)
![](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)