@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.08 kB
JavaScript
import { isZoneId } from "../../internal/inputChecks.js";
import { resolveUnixEpochUnitOptions, unixEpochToInstant } from "../../internal/unixEpochValue.js";
// src/unix/convert/convertUnixToZoned.ts
/**
* Convert a unix epoch value to a zoned ISO 8601 datetime string.
*
* - Converts to ZonedDateTime using the specified timezone (required; an unknown zone returns "").
* - `value` is a safe integer or a string of optionally negative ASCII digits; anything else, or an
* instant outside the Temporal range, returns "".
* - An explicit `undefined` `options` is the same as omitted; a non-object `options` (such as a
* bare `"seconds"` string) returns "".
* - An offset with seconds (`-00:44:30`) returns `""`. A written zone cannot carry seconds (RFC
* 9557 §4.1), so the result could not name it. Pass the IANA name, or call
* `fromOffsetInstant({ instant, offset })` for the local time with its full offset and no
* bracket.
*
* @param value epoch value: a safe integer or a digit string
* @param timeZone IANA name or a UTC offset to the minute (what `isValidTimeZone` accepts)
* @param options optional: how `value` is read
* @returns zoned ISO 8601 string or "" on invalid
*
* @example convertUnixToZoned(1709164800000, "Asia/Kolkata") // "2024-02-29T05:30:00+05:30[Asia/Kolkata]"
* @example convertUnixToZoned(1709164800, "UTC", { epochUnit: "seconds" }) // "2024-02-29T00:00:00+00:00[UTC]"
* @example convertUnixToZoned("-1", "UTC") // "1969-12-31T23:59:59.999+00:00[UTC]"
* @example convertUnixToZoned(1709164800, "UTC", "seconds" as never) // "" (options must be an object)
* @example convertUnixToZoned(NaN, "UTC") // ""
*/
function convertUnixToZoned(value, timeZone, options) {
try {
const epochUnit = resolveUnixEpochUnitOptions(options);
if (epochUnit === null || !isZoneId(timeZone)) return "";
const instant = unixEpochToInstant(value, epochUnit);
if (instant === null) return "";
try {
return instant.toZonedDateTimeISO(timeZone).toString();
} catch {
return "";
}
} catch {
return "";
}
}
export { convertUnixToZoned };