@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) • 1.73 kB
JavaScript
import { nowInstant } from "../../internal/temporalCompat/clock.js";
import { isDateTimeUnitName } from "../../internal/unitNames.js";
import { resolveDateTimeUnit } from "../../internal/resolveDateTimeUnit.js";
import { isoWeekOfYear, zonedNowUnitValue } from "../../internal/zonedNowUnitValue.js";
// src/utc/get/getUtcNowUnit.ts
function isValidUtcNowUnit(unit) {
return isDateTimeUnitName(unit) || ["dayOfWeek"].includes(unit);
}
/**
* Return the requested unit value from the current UTC instant.
*
* - Valid units: "year", "month", "week", "day", "dayOfWeek", "hour", "minute", "second", "millisecond", "microsecond", "nanosecond".
* - Uses nowInstant() converted to UTC.
* - `unit` accepts the singular or plural name of a Temporal unit (`"hour"` or `"hours"`), as Temporal
* does; `"dayOfWeek"` has no plural.
* - Returns "" on invalid unit or failure.
* - 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 unit unit to extract from current utc instant
* @returns string representation of the requested unit or "" on invalid
*
* @example getUtcNowUnit("year") // "2024"
* @example getUtcNowUnit("month") // "02"
* @example getUtcNowUnit("hours") // "14", if the UTC time is 14:xx (plural unit name)
* @example getUtcNowUnit("invalid") // ""
*/
function getUtcNowUnit(unit) {
if (typeof unit !== "string") return "";
const resolvedUnit = resolveDateTimeUnit(unit);
if (!isValidUtcNowUnit(resolvedUnit)) return "";
try {
const now = nowInstant().toZonedDateTimeISO("UTC");
return zonedNowUnitValue(now, resolvedUnit, isoWeekOfYear);
} catch {
return "";
}
}
export { getUtcNowUnit };