1

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?

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
Anralore
  • 103
  • 1
  • 9
  • If the notifications go to or from a server, could your JavaScript code then also get the correct time from that server? – Ole V.V. Jul 26 '20 at 09:51
  • There are also some answers [in this question](https://stackoverflow.com/questions/1638337/the-best-way-to-synchronize-client-side-javascript-clock-with-server-date) that might be helpful. It's a bit dated (no pun intended), but has some good tips. – JoshG Jul 26 '20 at 10:04

1 Answers1

0

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).

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335