views:

653

answers:

4

I was wondering if Javascript date/time functions will always return correct, universal dates/times or whether, Javascript being a client-side language, they are dependent on what the client machine has its date set to.

If it is dependent on the client machine, what is the best way to get the correct universal time?

+3  A: 

The methods do what they're documented to do. The best way to get UTC info is obviously to use the UTC methods:

getUTCFullYear(), getUTCMonth(), getUTCDate(), etc.

Matthew Flaschen
+2  A: 

or whether, Javascript being a client-side language, they are dependent on what the client machine has its date set to.

Yes, this is correct.

If it is dependent on the client machine, what is the best way to get the correct universal time?

To get the time/date from an authoritative source, not from a client machine.

matt b
Client time data is not trustworthy for critical applications. But I think the OP already knows that.
Matthew Flaschen
Is there an authoritative source that exposes an API?
rick
It'd be best to do it yourself by having your server sync up using ntp.
Richard Levasseur
+2  A: 

Javascript only knows as much about the correct time as the environment it is currently running within, and Javascript is client-side.

So, Javascript is at the mercy of the user having the correct time, AND timezone, settings on the PC on which they are browsing.

If the user has the incorrect time zone, but correct time, then functions depending on time zones like getUTCDate() will be incorrect.

If the user has the incorrect time, then all time-related functions in Javascript will be incorrect.

One could make the argument, however, that if the user wanted correct times on their PC they would have set the correct time. The counter to that is that the user may not know how to do that.

thomasrutter
+1  A: 

As thomasrutter has said javascript date functions are reliant on the client's machine. However if you want to get an authoritative date you could make and ajax request to your server that just returns the date string. You can then convert the date string into a date object with the following

var ds = ... // Some ajax call
var d = new Date(ds);
Alex