MCPcopy
hub / github.com/date-fns/date-fns / tzOffset

Function tzOffset

pkgs/tz/src/tzOffset/index.ts:22–48  ·  view source on GitHub ↗
(timeZone: string | undefined, date: Date)

Source from the content-addressed store, hash-verified

20 * @returns UTC offset in minutes (e.g., `480` for date in UTC+8).
21 */
22export 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
50const offsetRe = /([+-]\d\d):?(\d\d)?/;
51

Callers 10

benchmark.tsFile · 0.90
test.tsFile · 0.90
constructorMethod · 0.90
getTimezoneOffsetMethod · 0.90
syncToInternalFunction · 0.90
adjustToSystemTZFunction · 0.90
targetInternalTimeFunction · 0.90
tests.tsFile · 0.90
tzScanFunction · 0.90
legacy.cjsFile · 0.85

Calls 2

calcOffsetFunction · 0.85
formatFunction · 0.50

Tested by

no test coverage detected