javascripttimeutcsystemtime

How does UTC work with Javascript and computers with wrong times?


I have been writing some JavaScript code that relies upon universal time. I have been doing this online with two computers. One of which is 24 minutes behind the other.

Example:

Computer 1: 25/07/2020, 21:57     Computer 2: 25/07/2020, 22:21

When both computers enter a UTC number they are still the equivalent of 24 minutes apart.

Computer 1: 1595710054892    Computer 2: 1595711497605

This difference in time is causing problems with my programme as it relies upon timed notifications.

Is there anyway to correct for this or will I just have to hope that computers that use my JavaScript code will all have the same time within their respective timezone?


Solution

  • If you can't trust the clock on the computer (which is, frankly, shocking for a network-connected system in 2020) then you need to get the current time from somewhere else.

    The standard way to do this would be to use the Network Time Protocol.

    A quick Google turns up this JavaScript implementation of an NTP client:

    var ntpClient = require('ntp-client');
     
    ntpClient.getNetworkTime("pool.ntp.org", 123, function(err, date) {
        if(err) {
            console.error(err);
            return;
        }
     
        console.log("Current time : ");
        console.log(date); // Mon Jul 08 2013 21:31:31 GMT+0200 (Paris, Madrid (heure d’été))
    });
    

    If you're dealing with JS in a browser, you won't be able to use the NTP protocol directly so you would need to proxy the request via some server-side code which would lose some accuracy (but assuming a reasonable network connection, that would be in the order of a few seconds rather than 10s of minutes).