javascriptdatetimestamputc

Accuracy of Date.now() in browsers


I've seen plenty of questions about how to get the date/time in JavaScript, and the answers always look something like

Date.now() returns the UTC timestamp in milliseconds

But how reliable is that value really? Is it just based on the system clock of whatever computer is running the browser? If so, it seems like it could vary arbitrarily far from true UTC time, but how much variation should be expected?. I know caring about accurate milliseconds is a lost cause, but what about on the order of seconds or minutes?


Solution

  • Is it just based on the system clock of whatever computer is running the browser?

    Right. It may well be completely inaccurate. For example, on my computer, whose clock is inaccurate, at this moment, Date.now() returns 1563724931361, which, when passed into new Date, gives:

    Sun Jul 21 2019 11:02:11 GMT-0500 (Central Daylight Time)

    Which is completely wrong.

    If the client wishes to present an inaccurate Date.now(), it's pretty trivial for them to do so, though usually, for most ordinary users, it'll be accurate, because most people have accurate clocks.

    How accurate? It depends on the hardware, on how long it was since their computer last requested the time from a time server, and on how long since the computer was turned on (either from power off or standby/hibernate), but most times, it won't be off by more than a minute.