I assume the browser's native new Date() is subject to errors in the client computer's datetime. In my current application, it would be easier if I can guarantee the datetime provided by a user's browser is acceptably accurate (i.e. +/- 3 seconds is fine).
Is there an API (via HTTP requests) that when queried, will return the current UTC date and time?
I don't mind if you have to sign up / spend money to use it / it's rate limited by origin.
I was imagining I might use the following code:
let ms_diff: number | undefined = undefined
async function get_datetime ()
{
if (ms_diff === undefined)
{
const start = new Date().getTime()
const text = await fetch("https://example.com/current_datetime").text()
const end = new Date().getTime()
// Perhaps retry once or twice if difference between
// `start` and `end` is too large.
// approximate datetime of when request was received at API
const simple_mean = (start + end) / 2
ms_diff = new Date(text).getTime() - simple_mean
}
return new Date(new Date().getTime() + ms_diff)
}
I found one: http://worldtimeapi.org/pages/examples.
I think the api easiest for you to implement is http://worldtimeapi.org/api/ip . This is what it sends:
{
"abbreviation": "PDT",
"client_ip": "206.110.20.18",
"datetime": "2021-09-13T08:32:18.636090-07:00",
"day_of_week": 1,
"day_of_year": 256,
"dst": true,
"dst_from": "2021-03-14T10:00:00+00:00",
"dst_offset": 3600,
"dst_until": "2021-11-07T09:00:00+00:00",
"raw_offset": -28800,
"timezone": "America/Los_Angeles",
"unixtime": 1631547138,
"utc_datetime": "2021-09-13T15:32:18.636090+00:00",
"utc_offset": "-07:00",
"week_number": 37
}
Warning: This is what the website says:
It is not recommended that this API be used for commercial applications. The API can go down from time-to-time, for relatively long periods. It is provided with no SLA, no guarantees, and no direct funding.