5

JavaScript's getTime() returns "the number of milliseconds since 1 January 1970 00:00:00 UTC".

Can I rely on this being similar across different machines? I don't need it to be accurate to the millisecond, just to a few seconds.

Or do I need to use an external time service API, as in this question?

Where does JavaScript get the current time from - is it dependent on the machine's clock?

Community
  • 1
  • 1
Richard
  • 31,629
  • 29
  • 108
  • 145

2 Answers2

6

Can I rely on this being similar across different machines?

No.

Where does JavaScript get the current time from

The system datetime on which this javascript runs.

Or do I need to use an external time service API, as in this question?

You could use the server's time and send it to the client.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • Every HTTP response from your server includes the server's idea of the current time (as of when it started generating the response). For your goal of "to a few seconds", this should be sufficient. Once you calculate the offset between server time and local time, you can expect that to be relatively stable over the short-term. (If you know the local time is 46s fast, it'll probably still be 46s fast a minute from now: you can use this assumption to avoid a *lot* of server pings to check the current time. In fact, good luck coding without that assumption, it's easy to make without realizing it.) – derobert Dec 01 '11 at 14:30
0

Javascript is definitely going to use the internal clock of the machine (where else could it possibly get this information?).

Whether it is safe depends on what you are writing and for what reason. If you do decide to use it to compare it across machines, make sure it is very fault taulerant, as this can easily be messed with.

riwalk
  • 14,033
  • 6
  • 51
  • 68