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.

45 lines (43 loc) • 2.04 kB
import { isOptionsArgument } from "../../internal/isObject.js"; import { frameWallClock, normalizeZoneFrame } from "../../internal/zoneFrame.js"; import { resolveUnixEpochUnit, unixEpochToInstant } from "../../internal/unixEpochValue.js"; // src/unix/convert/convertUnixToPlainDate.ts /** * Convert a Unix timestamp to a plain date string in the format "YYYY-MM-DD". * * - Converts to PlainDate in `timeZone`. * - `value` is a safe integer or a string of optionally negative ASCII digits; anything else returns * "". * - Returns "" for invalid input. * * @param value Unix epoch: a safe integer or a digit string * @param options optional: how `value` is read and the zone its wall clock is read in * @returns plain date string in "YYYY-MM-DD" format or "" on invalid input * * @example convertUnixToPlainDate(1709164800000, { timeZone: "UTC" }) // "2024-02-29" * @example convertUnixToPlainDate(1709164800, { epochUnit: "seconds", timeZone: "UTC" }) // "2024-02-29" * @example convertUnixToPlainDate(-1, { timeZone: "UTC" }) // "1969-12-31" * @example convertUnixToPlainDate(1709164800000) // "2024-02-29" (UTC by default) * @example convertUnixToPlainDate("1709164800", { epochUnit: "second", timeZone: "Asia/Tokyo" }) // "2024-02-29" * @example convertUnixToPlainDate(1709164800000, { timeZone: "Asia/Tokio" }) // "" (unknown zone) * @example convertUnixToPlainDate(NaN) // "" * @example convertUnixToPlainDate(1800000, { timeZone: "-00:44:30" }) // "1969-12-31" (a stored offset with seconds) */ function convertUnixToPlainDate(value, options) { try { if (!isOptionsArgument(options)) return ""; const epochUnit = resolveUnixEpochUnit(options?.epochUnit); const frame = normalizeZoneFrame(options?.timeZone); if (epochUnit === null || frame === null) return ""; const instant = unixEpochToInstant(value, epochUnit); if (instant === null) return ""; try { return frameWallClock(instant, frame).toPlainDate().toString(); } catch { return ""; } } catch { return ""; } } export { convertUnixToPlainDate };