Search code examples
javascriptdatetimentp

How to get the current time from an NTP server?


Issue

I've seen a few ways to do this but not in pure JavaScript.

After sending a fetch request to the server I get the HTML of the website, not the necessary time. Parsing it in any way doesn't seem to help since it's just the markup of the website and it doesn't seem to contain it anywhere.

I tried using Cloudfare's and Google's ntp, also using Date() is not sufficient for me since it uses system time.

What am I doing wrong?

Here's my code

const ntpServerUrl = 'https://time.cloudflare.com';

fetch(ntpServerUrl)
    .then(response => response.text())
    .then(data => {
        console.log(data)
        const ntpTime = parseFloat(data);

        const localTime = new Date(ntpTime * 1000);

        console.log('Local Time:', localTime);
    })
    .catch(error => {
        console.error('Error fetching NTP time:', error);
    });

Solution

  • You're making an HTTP request, to an HTTP server, using a URL with the HTTP scheme, using fetch (which is an HTTP client).

    If you want to make an NTP request then you have use an NTP client. npm lists a number of NTP libraries.

    (Note that JS running in a web browser will be unlikely to be able to make NTP requests due to the usual limits on networking APIs).