UNPKG

@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.

234 lines (221 loc) • 15.3 kB
--- name: gmt-basics description: > Core date/time basics — get current values, parse components, read ISO week, ordinal, quarter and fiscal-period identifiers, format for display, format relative time, compare dates, and validate strings/timezones/intervals. Reads the docs site (llms.txt and each page's .md twin) and the installed package's JSDoc for API details; this skill is a routing pointer, not an API dump. sources: - 'northguild/gmt:apps/dox/src/content/docs/guides/core-date-operations/get-current.mdx' - 'northguild/gmt:apps/dox/src/content/docs/guides/core-date-operations/parsing.mdx' - 'northguild/gmt:apps/dox/src/content/docs/guides/core-date-operations/formatting.mdx' - 'northguild/gmt:apps/dox/src/content/docs/guides/core-date-operations/relative-time.mdx' - 'northguild/gmt:apps/dox/src/content/docs/guides/core-date-operations/comparisons.mdx' - 'northguild/gmt:apps/dox/src/content/docs/guides/core-date-operations/validation.mdx' - 'northguild/gmt:apps/dox/src/content/docs/guides/core-date-operations/month-day-values.mdx' - 'northguild/gmt:apps/dox/src/content/docs/guides/zoned-date-operations/calendar-boundaries.mdx' - 'northguild/gmt:packages/gmt/src/plain/get/index.ts' - 'northguild/gmt:packages/gmt/src/plain/parse/index.ts' - 'northguild/gmt:packages/gmt/src/types/two-digit-year.ts' - 'northguild/gmt:packages/gmt/src/plain/format/index.ts' - 'northguild/gmt:packages/gmt/src/plain/locale/index.ts' - 'northguild/gmt:packages/gmt/src/plain/compare/index.ts' - 'northguild/gmt:packages/gmt/src/plain/validate/index.ts' - 'northguild/gmt:packages/gmt/src/zoned/get/index.ts' - 'northguild/gmt:packages/gmt/src/zoned/format/index.ts' - 'northguild/gmt:packages/gmt/src/zoned/validate/index.ts' - 'northguild/gmt:packages/gmt/src/zoned/parse/index.ts' - 'northguild/gmt:packages/gmt/src/utc/parse/index.ts' - 'northguild/gmt:packages/gmt/src/instant/parse/index.ts' - 'northguild/gmt:packages/gmt/src/instant/validate/index.ts' - 'northguild/gmt:packages/gmt/src/utc/validate/index.ts' - 'northguild/gmt:packages/gmt/src/unix/get/index.ts' - 'northguild/gmt:packages/gmt/src/utc/get/index.ts' - 'northguild/gmt:packages/gmt/src/calendar/calculate/index.ts' - 'northguild/gmt:packages/gmt/src/calendar/validate/index.ts' metadata: type: core library: '@northguild/gmt' library_version: '1.23.1' --- # GMT Basics Use this skill when the task touches core date/time read operations: getting the current time, parsing components out of a date string, formatting for display, producing human-friendly relative strings, comparing two values, or validating input before you act on it. ## When to load - The user needs "now" as an ISO string, or a formatted/localized display value. - The user wants to extract a year/month/day/hour from a date string. - The user needs the ISO week, ordinal, quarter or retail-calendar period a date falls in — a week number on a vessel schedule, a 4-5-4 fiscal period. - The user needs "yesterday" or "in 2 hours" style output. - The user is comparing or sorting two date strings. - The user wants to guard a call with a validity check first. ## Core rules 1. **ISO 8601 strings in.** Public APIs consume ISO strings, IANA timezone ids, or numeric Unix epochs — never `new Date()`. 2. **Sentinel returns, never throws.** `""` for strings, `null` for numbers, `false` for booleans, `[]` for arrays. Always check before using. This holds for a `null` or wrong-typed argument too (`addDate(x, null)` is `""`), so a `try`/`catch` around a GMT call is dead code. Two calls cannot fail and have no `null` to check: `getUnixNow()` with no options or with `epochUnit` set to a `UnixUnit`, and `x12TimeCodeZone` with an `X12ZoneTimeCode`. 3. **Read the docs site.** This skill is a routing pointer. For full API signatures, locale matrices, and code examples, read these: - `https://northguild.dev/gmt/llms.txt` is the map of every docs page. - Each page has a `.md` twin that holds its text, for example `https://northguild.dev/gmt/guides/core-date-operations/parsing.md`. - The JSDoc of the function you intend to call ships in the installed package: `node_modules/@northguild/gmt/dist/**/*.d.ts`. ## Key functions - **Current values**: `getNow`, `getToday`, `getUtcNow`, `getUnixNow`, `getSystemTimeZone`, `getTimeZones` - **A length of time from now** (`{ days: 90 }`, never negative; the name gives the direction): `getUnixIn` / `getUnixAgo`, `getUtcIn` / `getUtcAgo`, `getDateIn` / `getDateAgo`, `getDateTimeIn` / `getDateTimeAgo`, `getTimeIn` / `getTimeAgo`, `getZonedIn` / `getZonedAgo` (zone first). Unix, UTC and zoned forms write whole seconds; a cookie `Expires` or a JWT `exp` is one call. A negative amount returns the sentinel, so a past date is `getUtcAgo`, not a negative `getUtcIn`. For seconds, an HTTP date or the seconds left until a stored time, see the `gmt-arithmetic` skill. - **Parsing**: `parseYearFromDate`, `parseMonthFromDate`, `parseDateTimeWithPattern`, `parseRfc3339`, `parseRfc2822`, `parseHttpDate`, `parseSqlDateTime`, `parseSqlOffsetDateTime` (`@northguild/gmt/instant/parse`: the `timestamptz` / `datetimeoffset` text a database prints, `2024-03-15 14:30:00+00`, read to `2024-03-15T14:30:00+00:00`) - **Calendar identifiers**: `getIsoWeekDate`, `getOrdinalDate`, `getQuarter`, `getFiscalPeriod` - **Formatting**: `formatDate`, `formatTime`, `formatDateTime`, `formatRelativeDate`, `formatCalendar`, `formatRfc3339`, `formatRfc2822`, `formatHttpDate`, `formatSqlDateTime` - **Month-day (`--MM-DD`) and year-month (`YYYY-MM`)**: `isValidMonthDay`, `parseMonthDay`, `parseMonthDayFromDate`, `parseMonthDayFromDateTime`, `parseMonthDayWithPattern`, `formatMonthDay`, `compareMonthDays`, `areMonthDaysEqual`, `monthDayToDate`; `isValidYearMonth`, `parseYearMonth`, `parseYearMonthFromDate`, `parseYearMonthFromDateTime`, `parseYearMonthWithPattern`, `formatYearMonth`, `compareYearMonths`, `areYearMonthsEqual`, `addYearMonth`, `subtractYearMonth`, `diffYearMonth`, `startOfYearMonth`, `endOfYearMonth`, `getDaysInYearMonth` - **Locale names**: `getLocaleMonthNames`, `getLocaleWeekdayNames`, `getLocaleMeridiems`, `getLocaleEraNames` - **Comparison**: `isAfterDate`, `isBeforeDate`, `areDatesEqual`, `areDatesEqualBy`, `isWeekend`, `isBusinessDay`, `nextWeekday` - **Validation**: `isValidDate`, `isValidTime`, `isValidTimeZone`, `isValidZonedDateTime`, `isValidDateInterval`, `isValidFiscalPattern`, `isValidFiscalCalendar`, `isValidFiscalExtraWeek`, `isValidFiscalYearLabel`, `hasSecond60` - **Interchange-format validation**: `isValidRfc3339DateTime`, `isValidRfc2822DateTime`, `isValidHttpDate`, `isValidSqlDateTime`, `isValidSqlOffsetDateTime` - **UTC timestamp validation**: `isValidUtcTimestamp` (a UTC instant written `YYYY-MM-DDTHH:MM:SS[.f]Z` and nothing else; it has no parser) - The core string validators take a value of any type and return `false` for a non-string. A value typed `unknown` narrows to `string` when the result is `true`. A typed union such as `string | null` gets a plain `boolean`. ## Common pitfalls - A birthday or a fixed holiday is a month-day, not a date in a made-up year. Store it as `--MM-DD` (`parseMonthDay("12-25")` gives `"--12-25"`), and ask for the date in a year with `monthDayToDate("--02-29", 2023)`, which gives `"2023-02-28"`. A card expiry or billing month is a year-month: `isValidYearMonth("2026-10")` is `true`, while `isValidDate("2026-10")` stays `false`. Do not append `-01` to make a date. `addYearMonth` takes `years` and `months` only; `{ days: 1 }` gives `""`. - `formatRelative*` measure from now when `reference` is omitted, so the output changes from day to day. Pass `reference` whenever the result must be deterministic. `largestUnit` takes a singular or plural unit name (`"hour"` or `"hours"`) from the units the function's values have: `formatRelativeDate` day to year, `formatRelativeTime` second to hour, the others second to year. Any other unit returns `""`. `roundingMethod` is `"floor"`, `"ceil"` or `"round"`: any other value returns `""`. - In a `parse*WithPattern` pattern, `''` is one literal quote, inside or outside quoted text (UTS #35), and not an empty separator: `"''yyyy-MM-dd''"` reads `"'2024-01-15'"`. Write adjacent fields with nothing between them, as in `"yyyyMMdd"`. - A `yy` token in a `parse*WithPattern` pattern needs the caller's hundred-year window: `{ yearWindow: 2000 }` reads `"03/15/24"` against `"MM/dd/yy"` as `"2024-03-15"`, and `"rolling"` is the hundred years around the current UTC year. A `yy` pattern with no `yearWindow` returns `""`; a pattern with no `yy` never reads the option. - `getZonedNow` reads `smallestUnit` only, and writes milliseconds when it is omitted or `undefined`. The string always carries the offset and the zone. - `parseDateWithPattern`, `parseRfc2822` and `parseHttpDate` return `""` on shape-valid-but-unreal dates such as 31 February (regex only proves shape; Temporal validates the real value). Parsers reject; only arithmetic clamps. - `parseRfc2822` reads everything RFC 5322 says a receiver must: comments, folding whitespace, any case, two-digit years and zone names such as `EST` (an unknown name reads as `+00:00`). `parseHttpDate` reads all three HTTP-date forms, including `rfc850-date` and `asctime-date`. Both return `""` when the day name contradicts the date (`"Sat, 15 Mar 2024 …"`), so do not synthesise a day name; omit it. The `rfc2822DateTime` and `httpDate` regexes stay strict and match only what GMT writes, so do not use them to pre-filter parser input. - To check an interchange string, call its validator, not its regex. `isValidRfc3339DateTime`, `isValidRfc2822DateTime`, `isValidHttpDate`, `isValidSqlDateTime` and `isValidSqlOffsetDateTime` are each true exactly when the parser returns a value. A regex proves shape only: `rfc3339DateTime.test("2023-02-29T10:00:00Z")` is `true` and `isValidRfc3339DateTime` returns `false` for it. - `isValidUtcTimestamp` matches no parser: it is a narrower `isValidUtc`. It is true only for a real UTC instant written `YYYY-MM-DDTHH:MM:SS[.f]Z`: a four-digit year `0000` to `9999`, upper-case `T` and `Z`, seconds, an optional dot fraction of one to nine digits, and nothing after the `Z`. Use it for a string headed for storage or for a reader that is not Temporal. `isValidUtc` also accepts a time without seconds, a comma before the fraction and an expanded `±YYYYYY` year; all three are `false` here. A numeric offset, `+00:00` included, is `false` too: `isValidRfc3339DateTime` checks the whole RFC 3339 grammar, with the same two GMT limits (no second `60`, at most nine fraction digits). The check is on the spelling and the instant. A reader's own range and precision still apply. - `formatRfc2822`, `formatHttpDate` and `formatRfc3339` return `""` for a year their grammar cannot hold (before 0000, or after 9999 for RFC 3339 and HTTP). `formatRfc3339` writes a sub-minute historical offset as the same instant at `+00:00`. Use Temporal's `toString()` when you need any year. - Text formatters follow ECMA-402 as Temporal amends it, so text equals the `…ToParts` result joined. `era` or `timeZoneName` alone keep the default fields. A plain value never shows a zone name, and a style for fields the type lacks (`timeStyle` on `formatDate`, `dateStyle` on `formatTime`) returns `""`. Zoned formatters return `""`/`[]` for a `timeZone` option: to show an instant in another zone, use `formatUtc(value, locale, { timeZone })`. - A second of `60` is invalid in every spelling (`T`, `t`, space, basic format), and validators return `false` for it. Two functions tell you about one. `hasSecond60` is the shape test: it is true when the whole string is one of GMT's own kinds with a second 60, real or not (`"2024-06-15T12:34:60Z"` is `true`). A spelling that is not a GMT kind (`t`, a space, basic format, `[foo=bar]`, trailing text) is `false`. `isLeapSecond`, from `timescale/`, is the table lookup: it is true only for the 27 inserted leap seconds (`"2016-12-31T23:59:60Z"` is `true`, `"2024-06-15T12:34:60Z"` is `false`). Only the `timescale/`, `gnss/` and `finance/` functions accept a second 60, and only a listed one; see the `gmt-integration`, `gmt-gnss` and `gmt-finance` skills. - `isValidTimeZone` accepts every IANA name, including single-component links such as `Japan`, `Zulu` and `EST5EDT`, and ignores case. It also accepts offset zone ids such as `"+05:00"`, as Temporal does. - `isLeapYear` and `getWeekNumber` take a `PlainDate` only: a date-time returns `false`/`null`. Pass `value.slice(0, 10)` for a date-time's date. - Week numbers are ambiguous across year boundaries — `getIsoWeekDate` returns the week-numbering year with the week so the pair can never drift apart, and `getWeekYear` reads that year on its own. - `getLocaleWeekYear` and `getWeeksInLocaleWeekYear` use the ISO rule (`minimalDays` 4) unless you pass `{ minimalDays }`: ECMA-402 no longer exposes a locale's value. CLDR's world default is `1` (`en-US` included), so pass `{ minimalDays: 1 }` for those locales. - The `calendar/` identifier functions take a **zoneless** date or datetime. An instant has no calendar date until you name a zone — floor it with `floorToZone` first, or convert it in the zone you mean. - `getFiscalPeriod`'s `yearEndsOn` states the year-end **rule** by example, not one year's end. One published 4-5-4 example (NRF, US) adds a 53rd week when "there are four or more days left in January", which is the Saturday nearest January 31: `"2026-01-31"`, a Saturday on January 31. - `getFiscalPeriod` also requires `extraWeek` and `yearLabel`, with no default, because published calendars disagree on both. `extraWeek` is the period a 53rd week is added to: `"firstPeriod"` (ONS, UK) or `"lastPeriod"` (NRF, US). `yearLabel` names the fiscal year: `"startYear"` (NRF, US), `"endYear"`, the year its last day falls in, or `"majorityYear"`, the calendar year holding the most of its days (ONS, UK); a 182/182 split goes to the end year. IFRS 18 27(c) (formerly IAS 1 51(c)) lets a period be identified by the date it ends, which supports `"endYear"` and the tie rule. `getQuarter` with options takes `fiscalYearStartMonth` and `yearLabel`, both required. A calendar missing a field returns `null`; check it with `isValidFiscalCalendar`. - `isWeekend` is locale-aware via `Intl.Locale.weekInfo`; `isBusinessDay` is a fixed Mon–Fri week (Sat–Sun off, CLDR's world default; ISO 8601 defines no weekend) with no locale and no holidays **until you pass it a `BusinessCalendar`** — `isBusinessDay(value, { weekend, holidays, timeZone })` states the weekend and holidays itself. See the `gmt-arithmetic` skill. ## References - [Docs map for agents (llms.txt)](https://northguild.dev/gmt/llms.txt) - [API reference](https://northguild.dev/gmt/reference/) - [Core date operations guides index](https://northguild.dev/gmt/guides/core-date-operations/) - [Core date operations guides](/guides/core-date-operations/get-current/)