Skip to content

chronos ​

@c9up/chronos: dates, durations, intervals, recurrence rules and public holidays, on a Rust engine that handles time zones, parsing and formatting. Guide: Dates.

Installation ​

bash
pnpm add @c9up/chronos

chronos has no provider and no configuration. In Node, the native engine comes as one small package per platform, @c9up/chronos-<platform>, for linux x64 and arm64 (glibc), macOS x64 and arm64, and Windows x64. @c9up/chronos lists them as optional dependencies, and your package manager installs only the one that matches your machine. No Rust toolchain is needed. Do not install with optional dependencies turned off (--no-optional, --omit=optional): the engine would be left out. In a browser, chronos runs its WASM build, which ships in @c9up/chronos itself.

There is no JavaScript fallback. Without the engine, the first call throws E_CHRONOS_ENGINE_REQUIRED, and its message names the package to install, for example @c9up/chronos-linux-x64-gnu.

Entry points ​

ImportContents
@c9up/chronosDateTime, Duration, Interval, range helpers, recurrence rules, holidays, Chronos, at
@c9up/chronos/atlasdateTimeAtlasAdapter, the column adapter for atlas

Exports ​

@c9up/chronos ​

ExportKindDescription
DateTimeclassAn immutable instant with a zone and a locale.
DurationclassAn immutable amount of time in calendar units.
IntervalclassA half-open span between two DateTimes.
inRangefunctioninRange(input: DateInput, range: DateRange, options?: RangeCompareOptions): boolean.
containsRangefunctioncontainsRange(outer: DateRange, inner: DateRange, options?: RangeCompareOptions): boolean.
overlapsRangefunctionoverlapsRange(a: DateRange, b: DateRange, options?: RangeCompareOptions): boolean.
analyzeRangefunctionanalyzeRange(a: DateRange, b: DateRange, options?: RangeCompareOptions): RangeRelation.
expandRRulefunctionexpandRRule(start: DateInput, rrule: string | RRuleBuild, options?: number | ExpandRRuleOptions): string[], or expandRRule(rule: string, options?) with DTSTART in the text. Occurrences as UTC ISO strings.
toRRuleStringfunctiontoRRuleString(rule: RRuleBuild): string: an RRULE: line from fields, each checked.
holidaysfunctionholidays(year: number, options: HolidayOptions): Holiday[]: the public holidays of a country (and Swiss canton) for a year.
isHolidayfunctionisHoliday(date: string | DateTime, options: HolidayOptions): boolean.
easterDatefunctioneasterDate(year: number): string: Gregorian Easter Sunday as YYYY-MM-DD, years 1583 to 9999.
SWISS_CANTONSconstThe 26 two-letter canton codes.
errorsnamespaceThe package's errors, one class per code, see Errors. Each is a flare Exception with a string code.
atfunctionat(input?: string | Date): DateTime.
ChronosconstShortcuts: at, now, parse, add, subtract, diff, inRange, rangeContains, rangesOverlap, rangeRelation, rrule, buildRRule.
DateInputtypestring | Date | DateTime.
DateUnittype'second' | 'minute' | 'hour' | 'day' | 'week' | 'month' | 'year'.
BoundUnittypeThe same units, for startOf, endOf, hasSame.
DateRangeinterface{ start: DateInput; end: DateInput }.
RangeCompareOptionsinterface{ inclusiveStart?: boolean; inclusiveEnd?: boolean }.
RangeRelationinterface{ overlaps; aContainsB; bContainsA; aStartInB; aEndInB; bStartInA; bEndInA }, all booleans.
CalendarPartsinterface{ year; month; day; hour; minute; second; millisecond; weekday; weekNumber; weekYear }.
RelativeUnittype'years' | 'months' | 'weeks' | 'days' | 'hours' | 'minutes' | 'seconds'.
RelativeUnitLiketypeA RelativeUnit, plural or singular.
RelativeRoundingtype'trunc' | 'expand' | 'round' | 'floor' | 'ceil'.
ToRelativeOptionsinterface{ base?; locale?; style?; numberingSystem?; unit?; round?; rounding?; padding? }.
ToRelativeCalendarOptionsinterface{ base?; locale?; style?; numberingSystem?; unit? }.
DurationObjectinterface{ years?; months?; weeks?; days?; hours?; minutes?; seconds?; milliseconds? }, all numbers.
DurationUnittypekeyof DurationObject.
DurationUnitLiketypeA DurationUnit, plural or singular.
RRuleBuildinterface{ freq; interval?; wkst?; byDay?; byMonthDay?; byMonth?; byWeekNo?; byYearDay?; bySetPos?; byHour?; byMinute?; bySecond?; count?; until? }.
ExpandRRuleOptionsinterface{ limit?: number; tzid?: string }: limit 1 to 10 000, default 100; tzid the zone whose wall clock the rule runs on.
Holidayinterface{ date: string; key: HolidayKey }.
HolidayKeytypeA stable holiday identifier ('new_year', 'easter_monday', 'national_day'…).
HolidayCountrytype'CH' | 'FR'.
HolidayOptionstype{ country: 'CH'; region?: SwissCanton } | { country: 'FR'; region?: undefined }.
SwissCantontypeOne of SWISS_CANTONS.

@c9up/chronos/atlas ​

ExportKindDescription
dateTimeAtlasAdapterconst{ consume(raw: unknown): DateTime | null; prepare(value: unknown): string | null }. Reads a string, Date, number or bigint into a DateTime; writes a DateTime as a UTC ISO string.

DateTime ​

new DateTime(input?: string | Date, zone = 'UTC'). Every method returns a new value.

MemberSignatureDescription
fromstatic from(input: DateInput): DateTimeFrom any input.
nowstatic now(zone?: string): DateTimeThe current instant.
localstatic local(year?: number, month = 1, day = 1, hour = 0, minute = 0, second = 0, millisecond = 0): DateTimeNow, or a wall clock, in the host's zone.
utcstatic utc(year?: number, month = 1, …): DateTimeSame, in UTC.
fromMillis / fromSeconds / fromUnixstatic fromMillis(ms: number): DateTimeFrom an epoch value.
fromJSDatestatic fromJSDate(date: Date): DateTimeFrom a Date.
fromISOstatic fromISO(text: string, options?: { zone?: string }): DateTimeStrict ISO 8601.
fromObjectstatic fromObject(obj: { year; month; day; hour?; minute?; second?; millisecond? }, options?: { zone?: string }): DateTimeFrom calendar fields, each range-checked.
fromSQLstatic fromSQL(input: string, options?: { zone?: string }): DateTimeFrom a SQL date or timestamp.
fromHTTPstatic fromHTTP(input: string): DateTimeFrom an HTTP date.
fromFormatstatic fromFormat(text: string, format: string, options?: { zone?: string; locale?: string }): DateTimeParse with a format.
zoneName / offset / localegettersZone name, UTC offset in minutes, locale.
setZonesetZone(zone: string, options?: { keepLocalTime?: boolean }): DateTimeSame instant in another zone, or the same wall clock with keepLocalTime.
toUTCtoUTC(): DateTime
setLocalesetLocale(locale: string): DateTime
isValidget isValid(): boolean
setset(values: { year?; month?; day?; hour?; minute?; second?; millisecond? }): DateTimeReplace calendar fields.
plus / minusplus(amount: number, unit: DateUnit): DateTime or plus(duration: Duration | DurationObject): DateTimeCalendar arithmetic.
diffdiff(other: DateInput, unit?: DateUnit | DurationUnit | 'millisecond' | ReadonlyArray<…>): DurationDifference, in milliseconds by default.
equals / isBefore / isAfterequals(other: DateInput): boolean
hasSamehasSame(other: DateInput, unit: BoundUnit): booleanSame calendar unit.
isSameDayisSameDay(other: DateInput): boolean
startOf / endOfstartOf(unit: BoundUnit): DateTime
isWithinisWithin(range: DateRange, options?: RangeCompareOptions): boolean
formatformat(pattern = 'YYYY-MM-DD HH:mm:ss'): stringYYYY-style tokens.
toFormattoFormat(pattern: string): stringyyyy-style tokens (yyyy-MM-dd HH:mm, dd LLL yyyy, EEEE, ZZ); 'quoted' text is literal.
toISO / toISOTimetoISO(options?: { suppressMilliseconds?: boolean; includeOffset?: boolean }): string
toISODate / toZonedISOtoISODate(): string
toSQL / toSQLDate / toSQLTimetoSQL(options?: { includeOffset?: boolean }): string
toDate / toMillis / toSeconds / valueOftoMillis(): number
toString / toJSONtoJSON(): stringISO string.
toLocaleStringtoLocaleString(locale?: Intl.LocalesArgument, options?: Intl.DateTimeFormatOptions): string
toRelativetoRelative(options?: ToRelativeOptions): string"in 3 days", "2 hours ago".
toRelativeCalendartoRelativeCalendar(options?: ToRelativeCalendarOptions): string"tomorrow", "last week".
calendarget calendar(): CalendarPartsEvery field at once.
year … millisecond, weekday, weekNumber, weekYear, ordinal, quarter, daysInMonth, daysInYear, isInLeapYeargettersCalendar fields on the value's wall clock.

Duration ​

MemberSignatureDescription
fromObjectstatic fromObject(obj: DurationObject): Duration
fromMillisstatic fromMillis(ms: number): Duration
fromISOstatic fromISO(iso: string): DurationP1DT2H.
years … millisecondsgettersEach unit.
getget(unit: DurationUnitLike): number
toObjecttoObject(): Required<DurationObject>
plus / minusplus(other: Duration | DurationObject | number): Duration
negatenegate(): Duration
mapUnitsmapUnits(fn: (value: number, unit: DurationUnit) => number): Duration
normalizenormalize(): DurationCarry overflow upward and balance mixed signs; years, months and weeks are kept.
shiftToshiftTo(...requested: DurationUnitLike[]): DurationExpress in the given units.
shiftToAllshiftToAll(): DurationSpread over every unit.
rescalerescale(): DurationThe largest units that fit.
asas(unit: DurationUnitLike): numberThe whole duration in one unit.
toMillis / valueOftoMillis(): number
toISO / toString / toJSONtoISO(): string
toFormattoFormat(pattern: string): string[bracketed] text is literal.
toHumantoHuman(): string"2 hours, 15 minutes", in English.

Interval ​

MemberSignatureDescription
fromDateTimesstatic fromDateTimes(start: DateInput, end: DateInput): Interval
after / beforestatic after(start: DateInput, duration: Duration | DurationObject | { amount: number; unit: DateUnit }): Interval
fromISOstatic fromISO(text: string, options?: { zone?: string }): Intervalstart/end.
mergestatic merge(intervals: readonly Interval[]): Interval[]Join overlapping and abutting intervals.
xorstatic xor(intervals: readonly Interval[]): Interval[]Time covered by exactly one.
start / endgetters
lengthlength(unit?: DurationUnit | DateUnit): numberIn milliseconds by default.
countcount(unit: DateUnit): numberUnits touched, partial ones included.
toDurationtoDuration(): Duration
contains / isBefore / isAftercontains(dt: DateInput): boolean
isEmptyisEmpty(): booleanZero length.
overlaps / engulfs / abutsStart / abutsEndoverlaps(other: Interval): boolean
intersectionintersection(other: Interval): Interval | null
unionunion(other: Interval): Interval
differencedifference(...intervals: Interval[]): Interval[]Parts none of them covers.
splitBysplitBy(duration: Duration | DurationObject | { amount: number; unit: DateUnit }): Interval[]
splitAtsplitAt(...dts: DateInput[]): Interval[]
toString / toJSONtoJSON(): { start: string; end: string }

Errors ​

CodeRaised when
E_CHRONOS_INVALID_YEAReasterDate or holidays got a year that is not an integer from 1583 to 9999.
E_CHRONOS_UNKNOWN_COUNTRYholidays or isHoliday got a country without a holiday calendar.
E_CHRONOS_UNKNOWN_REGIONThe region is not a Swiss canton code, or a region was given for FR.
E_CHRONOS_INVALID_DATEA date that does not exist or does not parse: 2026-02-30, a field out of range, a string fromFormat cannot match, an Invalid Date, a NaN instant; or isHoliday got a string that is not YYYY-MM-DD.
E_CHRONOS_ENGINE_REQUIREDThe Chronos engine (the NAPI binary in Node, the WASM build in a browser) did not load.
E_CHRONOS_INVALID_ARGUMENTAn argument has the wrong type (fromMillis("12"), fromFormat without a string, expandRRule(rule, options) without the rule text), or toRelative got an unknown rounding.
E_CHRONOS_OUT_OF_RANGEA value or a plus/minus result falls outside years 0000-9999.
E_CHRONOS_CONFLICTING_FIELDSA format mixes fields that contradict each other: a meridiem with a 24-hour hour, week fields with year/month/day, an ordinal with month/day.
E_CHRONOS_UNSUPPORTED_UNITA unit chronos does not know (fortnight) was given to plus, diff, toRelative, Duration or an Interval method.
E_CHRONOS_MISSING_UNITplus(amount) / minus(amount) without a unit, or diff / toRelative with an empty unit list.
E_CHRONOS_INVALID_UNIT_VALUEA unit amount is not a finite number (NaN, Infinity, a string).
E_CHRONOS_INVALID_DURATIONA duration that cannot be read or used: an ISO 8601 duration that does not parse, a value that is not an object of units, a non-positive splitBy step.
E_CHRONOS_INVALID_INTERVALAn Interval whose start is after its end, or an ISO 8601 interval that does not parse.
E_CHRONOS_INVALID_RANGEA DateRange given to inRange, containsRange, overlapsRange or analyzeRange starts after it ends.
E_CHRONOS_INVALID_LOCALEsetLocale got a tag Intl does not accept.
E_CHRONOS_INVALID_RRULEtoRRuleString (or expandRRule with a structured rule) got a field it cannot write into the rule text.
E_CHRONOS_INVALID_RRULE_LIMITThe expandRRule limit is not a positive integer.
E_CHRONOS_RRULE_LIMIT_EXCEEDEDThe expandRRule limit is above the 10,000 cap.
E_CHRONOS_INVALID_COLUMN_VALUEThe atlas DateTime column adapter read a database value of an unexpected type, or was asked to store something other than a DateTime.
E_CHRONOS_UNKNOWN_ZONEA zone the tz database does not know: new DateTime(input, zone), DateTime.now(zone), setZone, fromSQL, the tzid of expandRRule or a TZID in its text.
E_CHRONOS_UNREADABLE_RRULEexpandRRule got rule text the engine cannot read or expand: an unknown or repeated property, a value out of range, no start, a rule over the size limit.
E_CHRONOS_INTERNALThe engine answered something chronos does not expect (a bug in chronos, not in your code).

Every code is on error.code, and each code is a class of the errors namespace: error instanceof errors.E_CHRONOS_INVALID_DATE, with import { errors } from '@c9up/chronos'. Each is a flare Exception.

The Rust engine's refusals reach you with the same codes: chronos reads the engine's message back into the matching error, the engine's own failure kept as cause.

Migration ​

  • ChronosError, ChronosTypeError and ChronosRangeError are gone. Replace instanceof ChronosError (or one of the other two) with a test on error.code, or with instanceof errors.E_CHRONOS_..., errors coming from @c9up/chronos.
  • A refusal is no longer a TypeError or a RangeError: catch (e) { if (e instanceof RangeError) ... } must test the code instead.
  • The engine's refusals no longer carry code: 'GenericFailure' with the code at the start of the message: an unknown zone is E_CHRONOS_UNKNOWN_ZONE, unreadable rule text E_CHRONOS_UNREADABLE_RRULE, a date-arithmetic result outside 0000-9999 E_CHRONOS_OUT_OF_RANGE, and E_CHRONOS_UNKNOWN_COUNTRY, E_CHRONOS_UNKNOWN_REGION, E_CHRONOS_INVALID_YEAR, E_CHRONOS_INVALID_DATE are on error.code, no longer in the message.

See also ​