【JS】页面显示服务器时间

本文介绍了一种前端页面实现实时显示服务器时间的方法,通过首次加载时与服务器进行时间同步,之后利用本地计时每秒更新显示时间,确保客户端与服务器时间的一致性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

基本思路是加载页面时首先与服务器进行时间同步,然后在这个时间的基础上每秒刷新页面显示时间

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>前端获取服务器时间并更新</title>
</head>
<body>
<p id="time"></p>
</body>
<script>
    var i = 0;
    var sysTime = null;
    //每秒更新页面显示时间
    var int = self.setInterval("handle()", 1000);

    function handle() {
        if (i == 0) {
            synchronization();
        } else {
            time();
        }
        i++;
    }

    //本地计算时间
    function time() {
        var curDate = new Date(sysTime);
        ;
        curDate.setSeconds(curDate.getSeconds() + 1);
        sysTime = curDate;
        document.getElementById("time").innerHTML = "服务器时间:" + curDate.getFullYear() + "-" + (curDate.getMonth() + 1) + "-" + curDate.getDate() + " " + curDate.getHours() + ":" + curDate.getMinutes() + ":" + curDate.getSeconds();
    }

    //同步服务器时间
    function synchronization() {
        var xhr = new XMLHttpRequest();
        if (!xhr) {
            xhr = new ActiveXObject("Microsoft.XMLHTTP");
        }
        xhr.open("HEAD", location.href, true);
        xhr.onreadystatechange = function () {
            var time = null,
                curDate = null;
            if (xhr.readyState == 2) {
                // 获取响应头里的时间戳
                time = xhr.getResponseHeader("Date");
                curDate = new Date(time);
                sysTime = curDate;
                document.getElementById("time").innerHTML = "服务器时间:" + curDate.getFullYear() + "-" + (curDate.getMonth() + 1) + "-" + curDate.getDate() + " " + curDate.getHours() + ":" + curDate.getMinutes() + ":" + curDate.getSeconds();
            }
        }
        xhr.send(null);
    }
</script>
</html>

参考:https://www.cnblogs.com/weekend001/p/3654084.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值