In JavaScript, you can get the client’s time zone and offset using the Intl.DateTimeFormat
and Date
objects. Here’s how you can retrieve the client’s time zone and the offset from UTC.
1. Getting the Client’s Time Zone
You can use the Intl.DateTimeFormat
object to get the time zone name:
// Get the client's time zone
const timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone;
console.log(timeZone); // Example output: "America/New_York"
This will give you the name of the time zone, such as "America/New_York"
, "Europe/London"
, or "Asia/Tokyo"
.
2. Getting the Client’s UTC Offset
To get the UTC offset (in minutes) of the client’s local time zone, use the Date
object’s getTimezoneOffset()
method.
// Get the client's UTC offset in minutes
const date = new Date();
const utcOffsetMinutes = date.getTimezoneOffset();
console.log(utcOffsetMinutes); // Example output: -300 (UTC-5 hours)
The getTimezoneOffset()
method returns the difference between the client’s local time and UTC in minutes. Positive values indicate that the local time zone is ahead of UTC, and negative values indicate that it is behind UTC.
3. Getting the UTC Offset with Hours and Minutes
If you want to display the UTC offset in a more human-readable format (e.g., +02:00
or -05:00
), you can do the following:
// Get the client's UTC offset in hours and minutes (formatted as +HH:mm or -HH:mm)
const offset = new Date().getTimezoneOffset();
const sign = offset > 0 ? '-' : '+';
const hours = Math.floor(Math.abs(offset) / 60);
const minutes = Math.abs(offset) % 60;
const formattedOffset = `${sign}${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}`;
console.log(formattedOffset); // Example output: "-05:00"
4. Combining Time Zone and UTC Offset
You can combine both the time zone name and the UTC offset into a single string:
const timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone;
const utcOffset = new Date().getTimezoneOffset();
const sign = utcOffset > 0 ? '-' : '+';
const hours = Math.floor(Math.abs(utcOffset) / 60);
const minutes = Math.abs(utcOffset) % 60;
const formattedOffset = `${sign}${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}`;
console.log(`Time Zone: ${timeZone}, UTC Offset: ${formattedOffset}`);
Summary of Methods
Intl.DateTimeFormat().resolvedOptions().timeZone
: Gets the time zone name (e.g.,"America/New_York"
).new Date().getTimezoneOffset()
: Gets the UTC offset in minutes (e.g.,-300
for UTC-5).- Custom formatting for offset: Convert the offset to a
+HH:mm
or-HH:mm
format.