Javascript Time Zone Date

I need a js Date object with the specified values ​​for date and year. I would expect a new Date("2000-01-01") to give me a Date object from 2000 as the value for getFullYear() , but if my computer’s settings are set to the time zone in Chicago, I get Fri Dec 31 1999 18:00:00 GMT-0600 (CST) , and for Buenos Aires: Fri Dec 31 1999 22:00:00 GMT-0200 (ARST) .

Is there a way to create a Date object, .getFullYear() returns the date we set in the constructor, regardless of what time zone is set on the user machine?

Update: I need this Date object to be used in another library (which calls its .getFullYear() method, so using UTC getters really doesn't help.

+6
source share
2 answers

When parsing a Date string in JavaScript, a value that is in the format YYYY-MM-DD is interpreted as a UTC value, not a local time value.

The key is that the parts are separated by a hyphen and that there is no time zone information in the line. The ECMAScript 5.1 specification says in §15.9.1.15 :

... The offset value for the missing time zone is "Z".

This means that if you do not specify an offset, it is assumed that you mean UTC.

Please note that since this is the opposite of what is specified in ISO-8601, this behavior has been changed in ECMAScript 2015 (6.0), which is specified in § 20.3.1.16 :

... If there is no time zone offset, the date-time is interpreted as local time.

Therefore, when this position of ES6 is implemented correctly, string values ​​of this format, which were previously interpreted as UTC, will be interpreted as local time. I wrote about it here .

The workaround is simple. Replace hyphens with a slash:

 var s = "2000-01-01"; var dt = new Date(s.replace(/-/g, '/')); 

Another workaround that is acceptable is to set the time of noon instead of midnight to a date. This will be analyzed as local time and far enough to avoid DST conflicts.

 var s = "2000-01-01"; var dt = new Date(s + "T12:00:00"); 

Alternatively, consider a library like moment.js , which is much more reasonable.

 var s = "2000-01-01"; var dt = moment(s, 'YYYY-MM-DD').toDate(); 
+13
source

You can write a new method in "Date.prototype" and use it to get a date that will include the local time zone offset.

  //return the date with depend of Local Time Zone Date.prototype.getUTCLocalDate = function () { var target = new Date(this.valueOf()); var offset = target.getTimezoneOffset(); var Y = target.getUTCFullYear(); var M = target.getUTCMonth(); var D = target.getUTCDate(); var h = target.getUTCHours(); var m = target.getUTCMinutes(); var s = target.getUTCSeconds(); return new Date(Date.UTC(Y, M, D, h, m + offset, s)); }; 
0
source

Source: https://habr.com/ru/post/984064/


All Articles