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.

41 lines (39 loc) • 2.35 kB
import { isOptionsArgument } from "../../internal/isObject.js"; import { unixUnitString } from "../../internal/unixWallClock.js"; // src/unix/parse/parseUnitFromUnix.ts /** * Extract a unit from a unix epoch value. * * - Valid units: "year", "month", "week", "day", "dayOfWeek", "hour", "minute", "second", "millisecond", "microsecond", "nanosecond". Temporal units may also be plural ("hours"). * - `value` is a safe integer or a string of optionally negative ASCII digits. * - `microsecond` and `nanosecond` are the 0–999 Temporal fields, zero-padded to 3 digits. * - Converts to ZonedDateTime then extracts the unit. * - Returns "" for invalid input. * - The `"year"` unit is written as Temporal writes a year: four digits (`"2024"`, `"0005"`), or a * sign and six digits outside 0000–9999 (`"+010000"`, `"-000005"`). * * @param value unix epoch in milliseconds or seconds: a safe integer, or a string of optionally negative ASCII digits * @param unit unit to extract (e.g. "year", "month", "hour") * @param options optional: how `value` is read, the zone its wall clock is read in and the first day of the week; a non-object value (such as `null`) is invalid * @returns extracted unit value as string, or "" on invalid input * * @example parseUnitFromUnix(1700000000000, "year") // "2023" * @example parseUnitFromUnix(-61996320000000, "year") // "0005" (1 June of year 5) * @example parseUnitFromUnix(1700000000, "hour", { epochUnit: "seconds", timeZone: "UTC" }) // "22" * @example parseUnitFromUnix(1704067200000, "week", { timeZone: "UTC" }) // "1" * @example parseUnitFromUnix(1704067200000, "week", { weekStartsOn: "sunday", timeZone: "UTC" }) // "1" * @example parseUnitFromUnix(-86400, "year", { epochUnit: "seconds", timeZone: "UTC" }) // "1969" * @example parseUnitFromUnix("1709217045123", "hours") // "14" (digit string, plural unit, UTC by default) * @example parseUnitFromUnix(1709217045123, "nanosecond") // "000" * @example parseUnitFromUnix("", "year") // "" (a blank string is not epoch 0) * @example parseUnitFromUnix(45870000, "minute", { timeZone: "-00:44:30" }) // "00" (a stored offset with seconds) */ function parseUnitFromUnix(value, unit, options) { try { if (!isOptionsArgument(options)) return ""; return unixUnitString(value, unit, options); } catch { return ""; } } export { parseUnitFromUnix };