@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.73 kB
JavaScript
import { nowInstant } from "../../internal/temporalCompat/clock.js";
import { isValidDateTimeUnit } from "../../plain/validate/isValidDateTimeUnit.js";
import { resolveDateTimeUnit } from "../../internal/resolveDateTimeUnit.js";
import { isoWeekOfYear, zonedNowUnitValue } from "../../internal/zonedNowUnitValue.js";
// src/unix/get/getUnixNowUnit.ts
function isValidUnixNowUnit(unit) {
return isValidDateTimeUnit(unit) || unit === "dayOfWeek";
}
/**
* Return the requested unit value from the current Unix timestamp in UTC.
*
* - Valid units: "year", "month", "week", "day", "dayOfWeek", "hour", "minute", "second", "millisecond", "microsecond", "nanosecond". Temporal units may also be plural ("hours").
* - `microsecond` and `nanosecond` are Temporal's 0–999 fields, zero-padded to 3 digits.
* - Uses nowInstant() converted to UTC zoned date time.
* - 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 unix timestamp
* @returns string representation of the requested unit or "" on invalid
*
* @example getUnixNowUnit("year") // "2024"
* @example getUnixNowUnit("month") // "02"
* @example getUnixNowUnit("months") // "02" (plural unit)
* @example getUnixNowUnit("invalid") // ""
*/
function getUnixNowUnit(unit) {
const resolved = typeof unit === "string" ? resolveDateTimeUnit(unit) : "";
if (!isValidUnixNowUnit(resolved)) return "";
try {
const now = nowInstant().toZonedDateTimeISO("UTC");
return zonedNowUnitValue(now, resolved, isoWeekOfYear);
} catch {
return "";
}
}
export { getUnixNowUnit };