Clock on webpage using server and system time?

前端 未结 8 900
无人及你
无人及你 2021-01-02 03:34

I need to add a clock to a web page. The clock needs to be synchronized with a server but I really don\'t want to have it constantly check the server as the page will be ope

相关标签:
8条回答
  • 2021-01-02 04:17
    <script>
    var ctoday = <?php echo time() * 1000 ?>;
    setInterval(function() {ctoday += 1000;},1000);
    function startTime() {
        var today = new Date(ctoday);
        var montharray = new Array("Jan","Feb","Mar","Abr","May","Jun","Jul","Ogu","Sep","Oct","Nov","Des");
        var h = today.getHours();
        var ampm = h >= 12 ? 'PM' : 'AM';
        h = h % 12;
        h = h ? h : 12;
        var m = today.getMinutes();
        var s = today.getSeconds();
        h = checkTime(h);
        m = checkTime(m);
        s = checkTime(s);
        document.getElementById('txt').innerHTML =
        checkTime(today.getDate())+" "+montharray[today.getMonth()]+" "+today.getFullYear() + " (" + ampm +" " + h + ":" + m + ":" + s +")"; 
        setTimeout(startTime, 1000);
    }
    
    function checkTime(i) {
        if (i < 10) {i = "0" + i};
        return i;
    }
    </script>
    <body onLoad="startTime();">
        <span id="txt"></span>
    </body>
    
    1. Create a Variable holds server time using PHP.
    2. Adds 1000 to the time stamp every 1 sec (1000 = 1 sec).
    3. now get the Hours.
    4. Now instantiate a new date with incremented time stamp.
    5. creates a months names
    6. detect AM or PM.
    7. convert the hours format from 24 to 12
    8. Getting the minutes
    9. Getting the seconds
    10. add 0 leads if hours less than 10
    11. add 0 leads if minutes less than 10
    12. add 0 leads if seconds less than 10
    13. Now concatenate all time and date and put them in the DOM element with ID "txt"
    14. repeat the function every 1 sec
    15. function adds 0 to lead the numbers < 10
    0 讨论(0)
  • 2021-01-02 04:23

    You can get the current time from the server on every page load, so even on first load you will have the current server time. After that, you may use a javascript timer on the page set to tick every second, and then you will virtually have a clock working synchronized with the server. You may also try applying offsets as suggested, but i wouldn't recommend since there's lag during postbacks.

    Ajax request might be an interesting option.

    Any doubts, you may also check this clock out!

    Also, W3Schools is a great reference for javascript.

    0 讨论(0)
提交回复
热议问题