我需要在HTML页面上用JS显示当前时间的代码
时间: 2023-10-12 22:25:24 浏览: 34
好的,以下是在HTML页面上用JS显示当前时间的代码:
```html
<!DOCTYPE html>
<html>
<head>
<title>显示当前时间</title>
</head>
<body>
<p id="time"></p>
<script>
function showTime() {
const now = new Date();
const year = now.getFullYear(); // 获取当前年份
const month = now.getMonth() + 1; // 获取当前月份(注意getMonth返回的是0-11,需要加1)
const day = now.getDate(); // 获取当前日期
const hour = now.getHours(); // 获取当前小时
const minute = now.getMinutes(); // 获取当前分钟
const second = now.getSeconds(); // 获取当前秒数
const timeStr = `${year}-${month}-${day} ${hour}:${minute}:${second}`;
document.getElementById("time").innerHTML = timeStr;
}
showTime(); // 页面加载时先显示一次时间
setInterval(showTime, 1000); // 每秒钟更新一次时间
</script>
</body>
</html>
```
以上代码会在页面上显示当前时间,并且每秒钟自动更新一次时间。