@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.
58 lines (56 loc) • 2.46 kB
JavaScript
import { nowZonedDateTimeISO } from "../../internal/temporalCompat/clock.js";
import { getSystemTimeZone } from "../../zoned/get/getSystemTimeZone.js";
import { isValidDateTimeUnit } from "../validate/isValidDateTimeUnit.js";
import { resolveDateTimeUnit } from "../../internal/resolveDateTimeUnit.js";
import { zonedNowUnitValue } from "../../internal/zonedNowUnitValue.js";
import { parseWeekFromDate } from "../parse/parseWeekFromDate.js";
// src/plain/get/getNowUnit.ts
function isValidPlainNowUnit(unit) {
return isValidDateTimeUnit(unit) || ["dayOfWeek"].includes(unit);
}
/**
* Return the requested current unit value using the system timeZone.
*
* - Valid units: "year", "month", "week", "day", "dayOfWeek", "hour", "minute", "second", "millisecond", "microsecond", "nanosecond".
* - Uses nowZonedDateTimeISO() to get current time in system timezone.
* - `unit` accepts the singular or plural name of a Temporal unit (`"hour"` or `"hours"`), as Temporal
* does; `"dayOfWeek"` has no plural.
* - Returns "" when unit is invalid or system timezone is unavailable.
* - 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 local time
* @returns string representation of the requested unit or "" on invalid
*
* @example getNowUnit("year") // "2024"
* @example getNowUnit("month") // "03"
* @example getNowUnit("week") // "11"
* @example getNowUnit("day") // "15"
* @example getNowUnit("dayOfWeek") // "5"
* @example getNowUnit("hour") // "14"
* @example getNowUnit("minute") // "30"
* @example getNowUnit("second") // "45"
* @example getNowUnit("millisecond") // "000"
* @example getNowUnit("microsecond") // "000"
* @example getNowUnit("nanosecond") // "000"
* @example getNowUnit("hours") // "14", if the local time is 14:xx (plural unit name)
* @example getNowUnit("invalid") // ""
*/
function getNowUnit(unit) {
if (typeof unit !== "string") return "";
const resolvedUnit = resolveDateTimeUnit(unit);
if (!isValidPlainNowUnit(resolvedUnit)) return "";
const timeZone = getSystemTimeZone();
if (!timeZone) return "";
let now;
try {
now = nowZonedDateTimeISO(timeZone);
} catch {
return "";
}
return zonedNowUnitValue(now, resolvedUnit, (zdt) => {
const w = parseWeekFromDate(zdt.toPlainDate().toString());
return w === null ? "" : w.toString();
});
}
export { getNowUnit };