fix(logs): respect TZ env var for timestamp display, fix Windows timezone (#21859)

This commit is contained in:
Robin Waslander
2026-03-02 15:44:37 +01:00
committed by GitHub
parent 944abe0a6c
commit 9f98d2766a
3 changed files with 96 additions and 66 deletions

View File

@@ -1,14 +1,36 @@
export function formatLocalIsoWithOffset(now: Date): string {
const year = now.getFullYear();
const month = String(now.getMonth() + 1).padStart(2, "0");
const day = String(now.getDate()).padStart(2, "0");
const h = String(now.getHours()).padStart(2, "0");
const m = String(now.getMinutes()).padStart(2, "0");
const s = String(now.getSeconds()).padStart(2, "0");
const ms = String(now.getMilliseconds()).padStart(3, "0");
const tzOffset = now.getTimezoneOffset();
const tzSign = tzOffset <= 0 ? "+" : "-";
const tzHours = String(Math.floor(Math.abs(tzOffset) / 60)).padStart(2, "0");
const tzMinutes = String(Math.abs(tzOffset) % 60).padStart(2, "0");
return `${year}-${month}-${day}T${h}:${m}:${s}.${ms}${tzSign}${tzHours}:${tzMinutes}`;
export function isValidTimeZone(tz: string): boolean {
try {
new Intl.DateTimeFormat("en", { timeZone: tz });
return true;
} catch {
return false;
}
}
export function formatLocalIsoWithOffset(now: Date, timeZone?: string): string {
const explicit = timeZone ?? process.env.TZ;
const tz =
explicit && isValidTimeZone(explicit)
? explicit
: Intl.DateTimeFormat().resolvedOptions().timeZone;
const fmt = new Intl.DateTimeFormat("en", {
timeZone: tz,
year: "numeric",
month: "2-digit",
day: "2-digit",
hour: "2-digit",
minute: "2-digit",
second: "2-digit",
hour12: false,
fractionalSecondDigits: 3 as 1 | 2 | 3,
timeZoneName: "longOffset",
});
const parts = Object.fromEntries(fmt.formatToParts(now).map((p) => [p.type, p.value]));
const offsetRaw = parts.timeZoneName ?? "GMT";
const offset = offsetRaw === "GMT" ? "+00:00" : offsetRaw.slice(3);
return `${parts.year}-${parts.month}-${parts.day}T${parts.hour}:${parts.minute}:${parts.second}.${parts.fractionalSecond}${offset}`;
}