Victor Zhou Victor Zhou - 5 months ago 24
Node.js Question

Javascript Date.now() consistency across machines / time zones

Let's say I have a node.js server running from New York, and I have a client connected to it from California using a web brwoser. How reasonably can I expect Date.now() called from the client to match Date.now() called from node.js on the server to within ~50-100 ms (assuming they're called at the exact same instant)? Theoretically Date.now() should always be consistent across machines and time zones since Date.now() "returns the number of milliseconds elapsed since 1 January 1970 00:00:00 UTC" right?

Answer

No, you cannot necessarily assume that the client and server time are in sync.

One of the reasons for that is Date.now() is based on the system time of the user's OS. You have no control over that, the time may be correct, may be off a little bit or even completely wrong.

You can try that yourself:

> Date.now()
1466809144962

> Date.now()
1403650777388

I ran Date.now() twice, once with the correct time set up in Windows. Then I changed the year of my system clock to 2014 and ran Date.now() again.

Never rely on the correctness of information that is under control of the user without server side validation.

Comments