我第一次的发布···系统时间

实时显示系统时间
<script>
    // 获取显示时间的元素
    const timeBox = document.getElementById('time-box');

    // 定义更新时间的函数
    function updateTime() {
        // 创建日期对象
        const now = new Date();
        
        // 获取年月日
        const year = now.getFullYear();
        const month = String(now.getMonth() + 1).padStart(2, '0'); // 月份从0开始,需+1,补0成两位
        const day = String(now.getDate()).padStart(2, '0'); // 日期补0成两位
        
        // 获取时分秒
        const hour = String(now.getHours()).padStart(2, '0');
        const minute = String(now.getMinutes()).padStart(2, '0');
        const second = String(now.getSeconds()).padStart(2, '0');
        
        // 拼接时间格式
        const timeStr = `${year}年${month}月${day}日 ${hour}:${minute}:${second}`;
        
        // 把时间插入到页面中
        timeBox.textContent = timeStr;
    }

    // 页面加载时立即执行一次,避免初始空白
    updateTime();
    // 每隔1000毫秒(1秒)执行一次更新函数,实现实时显示
    setInterval(updateTime, 1000);
</script>
posted @ 2026-03-11 21:13  窦立浩  阅读(2)  评论(0)    收藏  举报