Where does JavaScript get a new Date() from?
Is it based on the client\'s local computers time settings or something else?
I can\'t find anywhere only where
It is the client (user') system date. The syntax is:
new Date();
new Date(value);
new Date(dateString);
new Date(year, month[, date[, hours[, minutes[, seconds[, milliseconds]]]]]);
The Date object is a datatype built into the JavaScript language. Date objects are created with the new Date( ) as shown below.
Once a Date object is created, a number of methods allow you to operate on it. Most methods simply allow you to get and set the year, month, day, hour, minute, second, and millisecond fields of the object, using either local time or UTC (universal, or GMT) time.
The ECMAScript standard requires the Date object to be able to represent any date and time, to millisecond precision, within 100 million days before or after 1/1/1970. This is a range of plus or minus 273,785 years, so JavaScript can represent date and time till the year 275755. Reference URL : https://www.tutorialspoint.com/javascript/javascript_date_object.htm
A JavaScript Date
object represents a moment in time, based on a number of milliseconds since The Epoch (Jan 1st 1970 at midnight UTC). Naturally, new Date
uses the clock of the environment where it's run to get that value. So if this is in a browser on my machine and my clock is set wrong, it will use my machine's incorrect time.*
They then have two sets of functions you can use to get information about that moment in time: Local timezone functions like getHours
, getMonth
, etc., and UTC functions like getUTCHours
, getUTCMonth
, etc. The local timezone functions work in the timezone of the environment. Naturally, the UTC functions are working in UTC.
So for instance, let's say someone is in California on March 3rd 2017 and does this at 11:30 a.m. exactly their time:
var dt = new Date();
console.log(dt.getHours()); // 11 -- e.g., 11 a.m.
console.log(dt.getUTCHours()); // 19 -- e.g., 7 p.m.
The underlying value of the object is 1488569400000, but the local timezone functions tell us that's 11 a.m. and the UTC functions tell us it's 7 p.m.
* (Although as James Thorpe points out, the spec is a bit vague about it, just saying it uses "the current time"; so in theory an environment could decide to have it use a time server other than the local machine. But...)
Yes, it's based on the local time of the device where the call is being evaluated, like pretty much any other language.
Given you don't need an internet connection to use JavaScript, it gets the current date & time (and by proxy, the UTC offset/locale) from the client's local environment. You can test this by changing your local clock.
Just remember to change it back..:)