@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.
53 lines (51 loc) • 2.7 kB
JavaScript
import { Temporal } from "./temporal.js";
import { isoYearString } from "./isoYearString.js";
// src/internal/zonedNowUnitValue.ts
/**
* One field of a zoned "now" as the `get*NowUnit` accessors return it: zero-padded to two digits
* (three for sub-second fields), the day of week unpadded, and the year as Temporal writes one
* (`isoYearString`: four digits, or a sign and six outside 0000–9999). The week number is the
* caller's, since the plain and zoned accessors read it through `parseWeekFromDate` and the utc and
* unix ones from the ISO date.
*
* @param now the current moment on the wall clock being read: a zoned date-time, or the plain wall
* clock of a stored UTC offset with seconds, which no time zone identifier can carry
* @param unit a singular unit, `dayOfWeek` included (already validated by the caller)
* @param week the week number for `now`, as a string
* @returns the field, or "" for any other unit
* @example zonedNowUnitValue(Temporal.ZonedDateTime.from("2024-03-05T07:08:09.012+00:00[UTC]"), "millisecond", () => "10") // "012"
* @example zonedNowUnitValue(Temporal.ZonedDateTime.from("2024-03-05T07:08:09+00:00[UTC]"), "week", () => "10") // "10"
* @example zonedNowUnitValue(Temporal.ZonedDateTime.from("2024-03-05T07:08:09+00:00[UTC]"), "quarter", () => "10") // ""
*/
function zonedNowUnitValue(now, unit, week) {
switch (unit) {
case "year": return isoYearString(now.year);
case "month": return now.month.toString().padStart(2, "0");
case "week": return week(now);
case "day": return now.day.toString().padStart(2, "0");
case "dayOfWeek": return now.dayOfWeek.toString();
case "hour": return now.hour.toString().padStart(2, "0");
case "minute": return now.minute.toString().padStart(2, "0");
case "second": return now.second.toString().padStart(2, "0");
case "millisecond": return now.millisecond.toString().padStart(3, "0");
case "microsecond": return (now.microsecond ?? 0).toString().padStart(3, "0");
case "nanosecond": return (now.nanosecond ?? 0).toString().padStart(3, "0");
default: return "";
}
}
/**
* The ISO 8601 week number of `now`'s date, the week the utc and unix `get*NowUnit` accessors read.
*
* @param now the current moment on the wall clock being read: a zoned date-time, or the plain wall
* clock of a stored UTC offset with seconds, which no time zone identifier can carry
* @returns the week number as a string
* @example isoWeekOfYear(Temporal.ZonedDateTime.from("2024-12-30T00:00:00+00:00[UTC]")) // "1"
*/
function isoWeekOfYear(now) {
return (Temporal.PlainDate.from({
year: now.year,
month: now.month,
day: now.day
}).weekOfYear ?? 0).toString();
}
export { isoWeekOfYear, zonedNowUnitValue };