前言
通过这样一个例子熟悉 JavaScript 中 Date 对象的常用方法
具体步骤
1.在页面的合适位置添加一个 id 为 clock 的<div>标记
<div id="clock"></div>
2.编写自定义的 JavaScript 函数 realSysTime(),在该函数中使用 Date 对象的相关方法获取系统日期
<script>
function realSysTime(clock) {
let now = new Date();
let year = now.getFullYear();
let month = now.getMonth() + 1; // 获取到的月份是从 0 开始的
let date = now.getDate();
let day = now.getDay(); // 获取星期
let hour = now.getHours();
let minus = now.getMinutes();
let sec = now.getSeconds();
let arr_week = new Array("星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六");
let week = arr_week[day];
let time = year + '年' + month + '月' + date + '日 ' + week + ' ' + formatTime(hour) + ':' + formatTime(minus) + ':' + formatTime(sec); // 时间拼接
clock.innerHTML = "当前时间:" + time;
}
</script>
3.为了能够保持时间是两位数,我们添加一个格式化时间的函数,目的是让小于 10 的时分秒在前面添加 0
<script>
// 格式化时间
function formatTime(time) {
time = time < 10 ? '0' + time : time;
return time;
}
</script>
4.在页面的载入事件 onload 中每隔 1 秒调用一次 realSysTime() 函数,实时显示系统时间
<script>
window.onload = function () {
window.setInterval("realSysTime(clock)", 1000);
}
</script>
完整代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>实时显示系统时间</title>
</head>
<body>
<div id="clock"></div>
<script>
function realSysTime(clock) {
let now = new Date();
let year = now.getFullYear();
let month = now.getMonth() + 1; // 获取到的月份是从 0 开始的
let date = now.getDate();
let day = now.getDay(); // 获取星期
let hour = now.getHours();
let minus = now.getMinutes();
let sec = now.getSeconds();
let arr_week = new Array("星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六");
let week = arr_week[day];
let time = year + '年' + month + '月' + date + '日 ' + week + ' ' + formatTime(hour) + ':' + formatTime(minus) + ':' + formatTime(sec); // 时间拼接
clock.innerHTML = "当前时间:" + time;
}
// 格式化时间
function formatTime(time) {
time = time < 10 ? '0' + time : time;
return time;
}
window.onload = function () {
window.setInterval("realSysTime(clock)", 1000);
}
</script>
</body>
</html>