Search code examples
javascriptdatetime

How to get date and time from server and use it as if it was the client's?


It is not a duplicated question. If you doubt, read it to the end.

Problem: I am creating a web page that is shown in a SmartTV browser and I can't rely or trust this device's clock. The time is always wrong and there is no date registry.

Solution: I use ajax to get my location's current date and time from a time server API. It sends back year, month, week day, month day, hour and minutes. I don't care about the exactly seconds.

How to: What I don't know how to do is to get this information and turn it to a working clock that refreshes in the browser when time and day goes up. I fetch the time server every hour to ensure it still in sync, but between this hour, how can I make the JavaScript counts the minutes, hours, days, months and years correctly?


Solution

  • Option 1: use setInterval(). For example:

    var numElapsedSeconds = 0;
    setInterval(function() {
        numElapsedSeconds++;
    }, 1000);
    

    Then add numElapsedSeconds to the last timestamp you received from the server and you have a (more or less) reliable current time.

    Option 2: when you get an update from the server, also check the local clock, figure out the delta, and from that point on use the delta with the local clock to get the "real" time. Even if the local time settings are wrong, I'm assuming that time still progresses at the same speed as on the server (maybe unless the user tweaks it all of a sudden). Not sure what your use-case is but maybe this could be reliable enough...

    You could also combine the two options for maximum accuracy (to compensate for the interval not being called exactly every 1000 milliseconds).