利用JavaScript实时显示系统时间

前言

通过这样一个例子熟悉 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>

显示效果

  • 1
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值