@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.
39 lines (37 loc) • 1.55 kB
JavaScript
import { Temporal } from "./temporal.js";
import { nowInstant } from "./temporalCompat/clock.js";
import { unixEpochToInstant } from "./unixEpochValue.js";
import { isValidUtc } from "../utc/validate/isValidUtc.js";
// src/internal/unixFormatReference.ts
/**
* Resolve the `reference` option of the unix formatters to an instant.
*
* - Omitted: now.
* - A string is a numeric unix epoch (`"1709164800000"`) or a UTC ISO string
* (`"2024-02-29T00:00:00Z"`). The numeric reading is tried first, matching `formatUnix`.
* - A number is a unix epoch in `epochUnit`.
*
* @param reference the option as given
* @param epochUnit the unit a numeric reference is read in
* @returns the instant, or null when the reference is neither form or the clock is unavailable
* @example resolveUnixFormatReference(1709164800, "seconds")?.toString() // "2024-02-29T00:00:00Z"
* @example resolveUnixFormatReference("2024-02-29T00:00:00Z", "milliseconds")?.toString() // "2024-02-29T00:00:00Z"
* @example resolveUnixFormatReference("yesterday", "milliseconds") // null
*/
function resolveUnixFormatReference(reference, epochUnit) {
if (reference === void 0) try {
return nowInstant();
} catch {
return null;
}
if (typeof reference !== "string") return unixEpochToInstant(reference, epochUnit);
const numericRef = unixEpochToInstant(reference, epochUnit);
if (numericRef !== null) return numericRef;
if (!isValidUtc(reference)) return null;
try {
return Temporal.Instant.from(reference);
} catch {
return null;
}
}
export { resolveUnixFormatReference };