UNPKG

@northguild/gmt

Version:

Date and time library for JavaScript and TypeScript, built on TC39 Temporal: time zones, DST, business days, ISO 8601 strings in and out. Never throws.

43 lines (41 loc) • 1.99 kB
import { Temporal } from "../../internal/temporal.js"; import { isOptionsArgument } from "../../internal/isObject.js"; import { frameWallClock, normalizeZoneFrame } from "../../internal/zoneFrame.js"; import { isValidUtc } from "../validate/isValidUtc.js"; // src/utc/convert/convertUtcToPlainDateTime.ts /** * Convert a UTC datetime string to a plain datetime string in the format "YYYY-MM-DDTHH:mm:ss". * * - Converts to the `timeZone` option's zone before extracting the datetime. * - The time is cut to the second: a fraction of a second in `value` is dropped. * - A year outside 0000–9999 is written with a sign and six digits (`+010000`, `-000005`), as * Temporal writes it, so the result is always a string `isValidDateTime` accepts. * - Returns "" for invalid input. * * @param value UTC datetime string (e.g., "2024-02-29T00:00:00Z") * @param options The time zone the value is read in * @returns plain datetime string in "YYYY-MM-DDTHH:mm:ss" format or "" on invalid input * * @example convertUtcToPlainDateTime("2024-02-29T00:00:00Z") // "2024-02-29T00:00:00" * @example convertUtcToPlainDateTime("2024-02-29T00:00:00Z", { timeZone: "Asia/Kolkata" }) // "2024-02-29T05:30:00" * @example convertUtcToPlainDateTime("invalid") // "" * @example convertUtcToPlainDateTime("+010000-01-01T00:00:00Z") // "+010000-01-01T00:00:00" (a year past 9999 has a sign and six digits) * @example convertUtcToPlainDateTime("1970-01-01T12:44:30Z", { timeZone: "-00:44:30" }) // "1970-01-01T12:00:00" (a stored offset with seconds) */ function convertUtcToPlainDateTime(value, options) { try { if (!isOptionsArgument(options)) return ""; const frame = normalizeZoneFrame(options?.timeZone); if (frame === null) return ""; if (!isValidUtc(value)) return ""; try { const instant = Temporal.Instant.from(value); return frameWallClock(instant, frame).toString({ smallestUnit: "second" }); } catch { return ""; } } catch { return ""; } } export { convertUtcToPlainDateTime };