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

    1. <!DOCTYPE html>
    2. <html>
    3. <head>
    4. <meta charset="utf-8">
    5. <title>前端获取服务器时间并更新</title>
    6. </head>
    7. <body>
    8. <p id="time"></p>
    9. </body>
    10. <script>
    11. var i = 0;
    12. var sysTime = null;
    13. //每秒更新页面显示时间
    14. var int = self.setInterval("handle()", 1000);
    15. function handle() {
    16. if (i == 0) {
    17. synchronization();
    18. } else {
    19. time();
    20. }
    21. i++;
    22. }
    23. //本地计算时间
    24. function time() {
    25. var curDate = new Date(sysTime);
    26. ;
    27. curDate.setSeconds(curDate.getSeconds() + 1);
    28. sysTime = curDate;
    29. document.getElementById("time").innerHTML = "服务器时间:" + curDate.getFullYear() + "-" + (curDate.getMonth() + 1) + "-" + curDate.getDate() + " " + curDate.getHours() + ":" + curDate.getMinutes() + ":" + curDate.getSeconds();
    30. }
    31. //同步服务器时间
    32. function synchronization() {
    33. var xhr = new XMLHttpRequest();
    34. if (!xhr) {
    35. xhr = new ActiveXObject("Microsoft.XMLHTTP");
    36. }
    37. xhr.open("HEAD", location.href, true);
    38. xhr.onreadystatechange = function () {
    39. var time = null,
    40. curDate = null;
    41. if (xhr.readyState == 2) {
    42. // 获取响应头里的时间戳
    43. time = xhr.getResponseHeader("Date");
    44. curDate = new Date(time);
    45. sysTime = curDate;
    46. document.getElementById("time").innerHTML = "服务器时间:" + curDate.getFullYear() + "-" + (curDate.getMonth() + 1) + "-" + curDate.getDate() + " " + curDate.getHours() + ":" + curDate.getMinutes() + ":" + curDate.getSeconds();
    47. }
    48. }
    49. xhr.send(null);
    50. }
    51. </script>
    52. </html>

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