(timeZone: string | undefined, date: Date)
| 20 | * @returns UTC offset in minutes (e.g., `480` for date in UTC+8). |
| 21 | */ |
| 22 | export function tzOffset(timeZone: string | undefined, date: Date): number { |
| 23 | try { |
| 24 | // Create `Intl.DateTimeFormat` with `"longOffset"` that gives us consistent |
| 25 | // date strings like `"5/19/2026, GMT-08:00"`. |
| 26 | const format = (offsetFormatCache[timeZone!] ||= new Intl.DateTimeFormat( |
| 27 | "en-US", |
| 28 | { timeZone, timeZoneName: "longOffset" }, |
| 29 | ).format); |
| 30 | |
| 31 | // Get `"-08:00"`. |
| 32 | const offsetStr = format(date).split("GMT")[1]!; |
| 33 | |
| 34 | // Avoid parsing the same offset string. |
| 35 | if (offsetStr in offsetCache) return offsetCache[offsetStr]!; |
| 36 | |
| 37 | // Calculate offset from `["-08", "00"]` and cache it. |
| 38 | return calcOffset(offsetStr, offsetStr.split(":")); |
| 39 | } catch { |
| 40 | // Fallback to manual parsing if the runtime doesn't support |
| 41 | // `±HH:MM/±HHMM/±HH`. See: https://github.com/nodejs/node/issues/53419. |
| 42 | if (timeZone! in offsetCache) return offsetCache[timeZone!]!; |
| 43 | const captures = timeZone?.match(offsetRe); |
| 44 | if (captures) return calcOffset(timeZone!, captures.slice(1)); |
| 45 | |
| 46 | return NaN; |
| 47 | } |
| 48 | } |
| 49 | |
| 50 | const offsetRe = /([+-]\d\d):?(\d\d)?/; |
| 51 |
no test coverage detected