@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.
43 lines (41 loc) • 1.87 kB
JavaScript
import { isOptionsArgument } from "../../internal/isObject.js";
import { frameWallClock, normalizeZoneFrame } from "../../internal/zoneFrame.js";
import { resolveUnixEpochUnit, unixEpochToInstant } from "../../internal/unixEpochValue.js";
// src/unix/convert/convertUnixToPlainTime.ts
/**
* Convert a Unix timestamp to a plain time string in the format "HH:mm:ss".
*
* - Converts to PlainTime in `timeZone`.
* - `value` is a safe integer or a string of optionally negative ASCII digits; anything else returns
* "".
* - Returns "" for invalid input.
*
* @param value Unix epoch: a safe integer or a digit string
* @param options optional: how `value` is read and the zone its wall clock is read in
* @returns plain time string in "HH:mm:ss" format or "" on invalid input
*
* @example convertUnixToPlainTime(1706659200000, { timeZone: "UTC" }) // "00:00:00"
* @example convertUnixToPlainTime(1706659200, { epochUnit: "seconds", timeZone: "UTC" }) // "00:00:00"
* @example convertUnixToPlainTime(-1, { timeZone: "UTC" }) // "23:59:59.999"
* @example convertUnixToPlainTime("1706659200000", { timeZone: "local" }) // system-zone wall clock, e.g. "09:00:00" in Asia/Tokyo
* @example convertUnixToPlainTime(NaN) // ""
* @example convertUnixToPlainTime(45870000, { timeZone: "-00:44:30" }) // "12:00:00" (a stored offset with seconds)
*/
function convertUnixToPlainTime(value, options) {
try {
if (!isOptionsArgument(options)) return "";
const epochUnit = resolveUnixEpochUnit(options?.epochUnit);
const frame = normalizeZoneFrame(options?.timeZone);
if (epochUnit === null || frame === null) return "";
const instant = unixEpochToInstant(value, epochUnit);
if (instant === null) return "";
try {
return frameWallClock(instant, frame).toPlainTime().toString();
} catch {
return "";
}
} catch {
return "";
}
}
export { convertUnixToPlainTime };