Determining Client Time Zone and Offset in JavaScript
When interacting with users from various time zones, it often becomes necessary to gather their time zone information. This includes getting both the time zone identifier and the offset from UTC or GMT.
Getting the Time Zone Identifier
Unfortunately, calculating the time zone using an offset is an unreliable approach. Time zones and daylight saving rules undergo frequent changes throughout the year, making it challenging to keep up with the variations.
Solution:
To reliably obtain the client's system IANA time zone in JavaScript, utilize:
console.log(Intl.DateTimeFormat().resolvedOptions().timeZone);
This approach returns the time zone identifier in a standardized IANA format. For instance, "Europe/London".
Getting the Offset from UTC or GMT
Once you have the time zone identifier, you can calculate the offset from UTC or GMT using:
let offset = new Date().getTimezoneOffset();
offset will represent the number of minutes the client's time zone is ahead of (or behind) UTC. A positive value indicates the client's time is ahead, while a negative value indicates it is behind.
The above is the detailed content of How Can I Determine a Client's Time Zone and UTC Offset in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!