简体   繁体   中英

Javascript timezone gmt and offset

I've read quite a bit about UTC/GMT and timezones when it comes to the Javascript Date class. But there is something that I do not understand:

const date = new Date('August 19, 1975 23:15:30 GMT+04:00');
const offset = date.getTimezoneOffset()

I thought the 'GMT+0400' states that my current date is 4 houres before the UTC time. So UTC would be 'August 19, 1975 19:15:30'

Why is 'offset' not -4? Is 'getTimezoneOffset' using the locale of my browser and if so, is there anyway that I can create a date in a specific timezone?

I thought the 'GMT+0400' states that my current date is 4 houres before the UTC time.

That GMT+0400 states that the text in the string is expressed in GMT+0400. But JavaScript Date instances don't let you specify what timezone they use. They use an offset in milliseconds from January 1st 1970 at midnight UTC, and provide functions to access the parts of the moment in time they represent either in units relative to the timezone of the system where the code is running ( getDate , getHours , etc.) or in units relative to UTC ( getUTCDate , getUTCHours ). getTimezoneOffset tells you what the difference between those is.

So although the text you gave the date to parse is expressed in GMT+0400, the timezone the instance uses for the local time functions is always the local timezone.

Here's an example of that fact: Two strings expressed in different timezones, but which result in equivalent Date instances:

 const s1 = "2020-08-31 12:30:00-0300"; const s2 = "2020-08-31 20:30:00+0500"; const d1 = new Date(s1); const d2 = new Date(s2); console.log(`s1 = ${s1}`); console.log(`d1 = ${d1.toString()}`); console.log(`s2 = ${s2}`); console.log(`d2 = ${d2.toString()}`); console.log(`d1 and d2 equivalent? ${d1.getTime() === d2.getTime()}`);

Is 'getTimezoneOffset' using the locale of my browser

Yes.

...and if so, is there anyway that I can create a date in a specific timezone?

No. But the new Temporal proposal will probably let you have Temporal.Absolute instances with a specified timezone. (It's still at an early stage, so things could change.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM