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.

37 lines (35 loc) • 1.53 kB
import { zonedDateTimeFrom } from "../../internal/zonedWallClock.js"; import { isValidZonedDateTime } from "../validate/isValidZonedDateTime.js"; import { resolveUnixEpochUnitOptions, toUnixEpoch } from "../../internal/unixEpochValue.js"; // src/zoned/convert/convertZonedToUnix.ts /** * Convert an ISO 8601 zoned datetime string to a unix epoch value in milliseconds (default) or seconds. * * - Uses Temporal.ZonedDateTime.toInstant to convert. * - Seconds floor toward −∞, as POSIX `time_t` counts whole elapsed seconds. * - A non-object `options` (such as a bare `"seconds"` string) returns null. * - Returns null for invalid input. * * @param value zoned ISO 8601 datetime string * @param options optional setting for the unit of the returned epoch value * @returns epoch number or null on invalid * * @example convertZonedToUnix("2024-02-29T12:34:56.789+00:00[UTC]") // 1709210096789 * @example convertZonedToUnix("2024-02-29T12:34:56.789+00:00[UTC]", { epochUnit: "seconds" }) // 1709210096 * @example convertZonedToUnix("2024-02-29T12:34:56.789+00:00[UTC]", "seconds" as never) // null (options must be an object) * @example convertZonedToUnix("invalid") // null */ function convertZonedToUnix(value, options) { try { const epochUnit = resolveUnixEpochUnitOptions(options); if (!isValidZonedDateTime(value) || epochUnit === null) return null; try { return toUnixEpoch(zonedDateTimeFrom(value).toInstant(), epochUnit); } catch { return null; } } catch { return null; } } export { convertZonedToUnix };