Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
137
rated 0 times [  141] [ 4]  / answers: 1 / hits: 26016  / 11 Years ago, wed, january 1, 2014, 12:00:00

To create Date object in UTC, we would write



new Date(Date.UTC(2012,02,30));


Without Date.UTC, it takes the locale and creates the Date object. If I have to create a Date object for CET running the program in some part of the world, how would I do it?


More From » node.js

 Answers
24

You don't create a JavaScript Date object in any specific timezone. JavaScript Date objects always work from a milliseconds-since-the-Epoch UTC value. They have methods that apply the local timezone offset and rules (getHours as opposed to getUTCHours), but only the local timezone. You can't set the timezone the Date object uses for its local methods.



What you're doing with Date.UTC (correctly, other than the leading 0 on 02) is just initializing the object with the appropriate milliseconds-since-the-Epoch value for that date/time (March 30th at midnight) in UTC, whereas new Date(2012, 2, 30) would have interpreted it as March 30th at midnight local time. There is no difference in the Date object other than the datetime it was initialized with.



If you need a timezone other than local, all you can do is use the UTC version of Date's functions and apply your own offset and rules for the timezone you want to use, which is non-trivial. (The offset is trivial; the rules tend not to be.)



If you go looking, you can find Node modules that handle timezones for you. A quick search for node timezone just now gave me timezone as the first hit. It also gave me links to this SO question, this SO question, and this list of timezone modules for Node.


[#73453] Monday, December 30, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
viridianaw

Total Points: 154
Total Questions: 94
Total Answers: 89

Location: South Georgia
Member since Sun, Aug 8, 2021
3 Years ago
;