Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are Javascript date/time functions dependent on the client machine?

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?

like image 264
rick Avatar asked Jun 19 '09 02:06

rick


People also ask

Where does JavaScript get time from?

JavaScript, however, understands the date based on a timestamp derived from Unix time, which is a value consisting of the number of milliseconds that have passed since midnight on January 1st, 1970. We can get the timestamp with the getTime() method.

How does JavaScript Date work?

JavaScript stores dates as number of milliseconds since January 01, 1970, 00:00:00 UTC (Universal Time Coordinated). Zero time is January 01, 1970 00:00:00 UTC.

What timezone does JavaScript Date use?

The JavaScript Date is always stored as UTC, and most of the native methods automatically localize the result.


2 Answers

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.

Edit Jun 2020: It is common now for operating systems to update the computer's system time automatically from a time server, significantly reducing the chances of incorrect time on the client. There is still a possibility of an incorrect time zone, but this too is often geo-detected somehow by systems during installation and/or is tied to the user's supplied country of residence in their relevant online account.

like image 111
thomasrutter Avatar answered Sep 25 '22 12:09

thomasrutter


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);
like image 45
Alex Avatar answered Sep 22 '22 12:09

Alex