@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.49 kB
JavaScript
import { Temporal } from "../../internal/temporal.js";
import { resolveUnixEpochUnitOptions, toUnixEpoch } from "../../internal/unixEpochValue.js";
import { isValidUtc } from "../validate/isValidUtc.js";
// src/utc/convert/convertUtcToUnix.ts
/**
* Convert a UTC Instant string to a unix epoch value in milliseconds or seconds.
*
* - Uses Temporal.Instant.from to parse.
* - Seconds floor toward −∞, so `"1969-12-31T23:59:59.5Z"` is second `-1` (POSIX `time_t`).
* - `options` must be an object or omitted: a non-object value (such as a bare `"seconds"` string)
* returns null.
* - Returns null for invalid input.
*
* @param value UTC Instant string
* @param options The unit of the returned epoch value
* @returns epoch number or null on invalid
*
* @example convertUtcToUnix("2024-02-29T00:00:00Z") // 1709164800000
* @example convertUtcToUnix("2024-02-29T00:00:00Z", { epochUnit: "seconds" }) // 1709164800
* @example convertUtcToUnix("1969-12-31T23:59:59.5Z", { epochUnit: "second" }) // -1
* @example convertUtcToUnix("2024-02-29T00:00:00Z", "seconds" as never) // null (options must be an object)
* @example convertUtcToUnix("invalid") // null
*/
function convertUtcToUnix(value, options) {
try {
const epochUnit = resolveUnixEpochUnitOptions(options);
if (!isValidUtc(value) || epochUnit === null) return null;
try {
return toUnixEpoch(Temporal.Instant.from(value), epochUnit);
} catch {
return null;
}
} catch {
return null;
}
}
export { convertUtcToUnix };