用js实现时间的显示功能,(Date) 要求能显示星期几,年月日,小时分钟秒
时间: 2023-06-23 21:09:49 浏览: 202
可以使用 JavaScript 中的 Date 对象来获取当前时间并进行格式化。以下是一个实现时间显示功能的示例代码:
```javascript
function showTime() {
const days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
const months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
const now = new Date();
const dayOfWeek = days[now.getDay()];
const month = months[now.getMonth()];
const dayOfMonth = now.getDate();
const year = now.getFullYear();
let hour = now.getHours();
let minute = now.getMinutes();
let second = now.getSeconds();
const ampm = hour >= 12 ? 'PM' : 'AM';
// 将小时转换为12小时制
hour = hour % 12;
hour = hour ? hour : 12;
// 在数字前补零
minute = padZero(minute);
second = padZero(second);
const timeString = `${dayOfWeek}, ${month} ${dayOfMonth}, ${year}, ${hour}:${minute}:${second} ${ampm}`;
document.getElementById("time").innerHTML = timeString;
// 每秒钟更新一次时间
setTimeout(showTime, 1000);
}
function padZero(num) {
return num < 10 ? '0' + num : num;
}
showTime();
```
在 HTML 中添加一个 `div` 元素,用于显示时间:
```html
<div id="time"></div>
```
然后就可以使用上述代码来显示当前时间,包括星期几、年月日、小时分钟秒。
阅读全文