Where does JavaScript get a new Date() from

后端 未结 4 589
生来不讨喜
生来不讨喜 2021-01-11 16:37

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

4条回答
  •  无人及你
    2021-01-11 17:25

    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...)

提交回复
热议问题