How do you detect the client's local timezone name and UTC offset in JavaScript? | A1Lab@FahadM to JavaScriptEnglish • 3 days ago

How do you detect the client's local timezone name and UTC offset in JavaScript?

message-square
0

To detect the client’s local timezone name and UTC offset in JavaScript, read the IANA timezone identifier ("Asia/Karachi", "America/New_York") via Intl.DateTimeFormat().resolvedOptions().timeZone and compute the UTC offset from new Date().getTimezoneOffset() (which returns the difference in minutes from UTC to local time with a reversed sign: positive west of UTC, negative east of UTC—so Asia/Karachi at UTC+5 returns -300). Because daylight saving time (DST) and historical offset changes can shift a zone’s offset across the year, always compute the offset for a specific reference Date rather than assuming a timezone has a single static offset.


1. Detecting the IANA Timezone Name and UTC Offset

Use Intl.DateTimeFormat().resolvedOptions().timeZone for the timezone identifier and date.getTimezoneOffset() to derive both raw minutes and formatted ±HH:MM offset strings:

// Detect the client's IANA timezone name and UTC offset for a given date
function getClientTimezoneInfo(referenceDate = new Date()) {
  if (!(referenceDate instanceof Date) || Number.isNaN(referenceDate.getTime())) {
    throw new TypeError("Expected referenceDate to be a valid Date instance.");
  }

  let timeZone = "UTC";
  try {
    const resolved = Intl.DateTimeFormat().resolvedOptions().timeZone;
    if (typeof resolved === "string" && resolved.length > 0) {
      timeZone = resolved;
    }
  } catch {
    timeZone = "UTC";
  }

  // getTimezoneOffset() is (UTC - local) in minutes, so invert sign for standard UTC±HH:MM
  const offsetMinutesFromUtc = -referenceDate.getTimezoneOffset();
  const sign = offsetMinutesFromUtc >= 0 ? "+" : "-";
  const absMinutes = Math.abs(offsetMinutesFromUtc);
  const hours = String(Math.floor(absMinutes / 60)).padStart(2, "0");
  const minutes = String(absMinutes % 60).padStart(2, "0");

  return {
    timeZone,
    utcOffsetMinutes: offsetMinutesFromUtc,
    utcOffsetString: `UTC${sign}${hours}:${minutes}`,
    isoOffset: `${sign}${hours}:${minutes}`
  };
}

// Example usage:
console.log(getClientTimezoneInfo());
// In Asia/Karachi: { timeZone: "Asia/Karachi", utcOffsetMinutes: 300, utcOffsetString: "UTC+05:00", isoOffset: "+05:00" }
  • Watch the sign inversion in getTimezoneOffset(): UTC+05:00 has getTimezoneOffset() === -300, whereas UTC-05:00 has getTimezoneOffset() === 300.
  • Fallback gracefully when unresolved: Older or restricted environments may omit timeZone, so defaulting to "UTC" or checking availability avoids crashes.

2. Computing the Offset for Any Specific IANA Timezone

When you need the exact offset of any IANA timezone (not just the current browser environment) at a specific timestamp—such as checking DST vs. standard time—format parts with Intl.DateTimeFormat using timeZoneName: "longOffset" or "shortOffset":

// Inspect offset and localized zone label for a specific IANA timezone & date
function getOffsetForZone(timeZone = "UTC", dateInput = new Date()) {
  if (typeof timeZone !== "string" || timeZone.length === 0) {
    throw new TypeError("Expected timeZone to be a non-empty string.");
  }

  const date = dateInput instanceof Date ? dateInput : new Date(dateInput);
  if (Number.isNaN(date.getTime())) {
    throw new RangeError("Expected a valid date input.");
  }

  const formatter = new Intl.DateTimeFormat("en-US", {
    timeZone,
    timeZoneName: "longOffset"
  });

  const parts = formatter.formatToParts(date);
  const offsetPart = parts.find((part) => part.type === "timeZoneName")?.value ?? "GMT";

  // Normalize "GMT+5:00" / "GMT-05:00" / "GMT" to standard ±HH:MM
  if (offsetPart === "GMT" || offsetPart === "UTC") {
    return { timeZone, gmtLabel: offsetPart, isoOffset: "+00:00" };
  }

  const match = offsetPart.match(/^(?:GMT|UTC)([+-])(\d{1,2})(?::?(\d{2}))?$/);
  if (!match) {
    return { timeZone, gmtLabel: offsetPart, isoOffset: null };
  }

  const [, sign, rawHours, rawMins = "00"] = match;
  const isoOffset = `${sign}${rawHours.padStart(2, "0")}:${rawMins.padStart(2, "0")}`;

  return { timeZone, gmtLabel: offsetPart, isoOffset };
}

// Example usage (comparing summer vs. winter offset in America/New_York):
console.log(getOffsetForZone("America/New_York", "2026-07-01T12:00:00Z")); // { ..., isoOffset: "-04:00" }
console.log(getOffsetForZone("America/New_York", "2026-01-15T12:00:00Z")); // { ..., isoOffset: "-05:00" }
  • DST changes offset dynamically: A single IANA zone like America/New_York shifts between -04:00 (EDT) and -05:00 (EST) depending on the date.
  • Avoid hardcoding offsets from zone names: Always resolve offsets against a concrete timestamp or IANA zone rule.

3. Spoofing, SSR, and Persistence Gotchas

Client timezone detection runs in the user’s runtime environment—so keep SSR differences, manual overrides, and data storage rules in mind:

// Non-mutating helper to attach client timezone context to outgoing API requests
function buildTimezoneContext(overrideZone = null) {
  const detected = getClientTimezoneInfo();
  const activeZone =
    typeof overrideZone === "string" && overrideZone.trim().length > 0
      ? overrideZone.trim()
      : detected.timeZone;

  return {
    detectedTimeZone: detected.timeZone,
    activeTimeZone: activeZone,
    utcOffsetMinutes: detected.utcOffsetMinutes,
    isoOffset: detected.isoOffset
  };
}

// Example usage:
console.log(buildTimezoneContext());
  • SSR vs. client mismatch: During server-side rendering, Intl.DateTimeFormat().resolvedOptions().timeZone reflects the server’s timezone (often UTC), not the visitor’s browser.
  • Store UTC timestamps, format with timezone on display: Persist UTC/ISO-8601 timestamps in databases and APIs, and apply the user’s timezone only when rendering or scheduling local times.