@luwiostack/datetime
v0.2.0
Published
A typed, DDD-style date & time domain — value objects (DateOnly, DateTime, Time, …), an Intl-based formatter, and a swappable engine (luxon today, Temporal-ready). Timezones from @luwiostack/timezone; clocks from @luwiostack/clock.
Readme
@luwiostack/datetime
A typed, DDD-style date & time domain. Instead of one god-object, dates are modelled as small,
always-valid value objects — Year, Month, Day, Hour, Minute, Second, Millisecond,
Time, DayOfWeek, YearAndMonth — composed into the two aggregates you reach for most,
DateOnly and DateTime (plus Instant, a zone-free moment), with Period (calendar time) and Duration (exact time) for arithmetic. Every factory throws on invalid input, so
an instance you hold is always a real date, and a DateTime can't exist without a timezone.
Part of LuwioStack. React-free. Timezones and Offset come from
@luwiostack/timezone (re-exported here, with OffsetFormatter / TimezoneFormatter); formatting is Intl-based. Built on top of it, in their own packages: clocks and React hooks
(@luwiostack/clock), time-of-day scheduling (@luwiostack/schedule) and age
rules (@luwiostack/age).
Install
npm install @luwiostack/datetime@luwiostack/timezone comes with it and is re-exported, so Timezone, Timezones, Offset,
zoneDifference, OffsetFormatter, TimezoneFormatter and the zone errors import from here too.
The engine (luxon today — see Temporal-readiness) is the one runtime
dependency, and only DateTime uses it: DateOnly, Time and the small value objects are plain
arithmetic.
Guarantees
- No invalid state. Private constructors; factories validate. Numeric fields take whole numbers in
range only (
NaN,1.5,Infinitythrow), years are0–9999(ISO output is always four digits and round-trips) — for aDateTimeboth its wall clock and its instant in UTC, so 9999-12-31T23:00 in Los Angeles (already year 10000 in UTC) throws —DateOnlyrejects 31 February. Every fallible factory has atry*twin (tryFrom,tryOf,tryFromIso8601, …) that returnsnullinstead of throwing — for the calendar fields,Time,DateOnly,YearAndMonth,Instant,Period,DurationandDateTime, as well asTimezone. - No look-alikes. The value objects are classes, not interfaces, and nominally typed: an object with the same shape doesn't type-check where a validated one is required.
- A
DateTimealways has a zone. Every constructor takes aTimezone(or derives one from aZ/offset in the string). Fields, offset and zone are checked against each other. Historic instants work in any zone: before zones were standardised the offset can have seconds (Kolkata in 1900 was+05:21:10), andtoIso8601()then prints them (1900-01-01T05:21:10.000+05:21:10) sofromIso8601(iso, zone)reads it back exactly. That form is not RFC 3339 —toIso8601Utc()always is. - Nothing silently adjusted. Building a
DateTimefrom a wall time a DST gap skips or an overlap repeats throws unless you pick adisambiguation; more than 3 fractional digits, a fractionalPeriod/Durationunit, or a result past year 9999 throws. (Calendar arithmetic —dt.add(Period…)— resolves such a wall time'compatible'by default, exactly like Temporal, and takes adisambiguationtoo.) - Independent of the machine.
DateOnlyis pure calendar arithmetic;DateTimetakes its zone explicitly, so no host timezone, locale or global setting can leak into results. CI runs the suite under severalTZvalues. - Instants compare as instants.
isBefore/isAfter/isSameInstantuse the absolute instant;equalsalso requires the same zone (aliases/casing count as one);compareWallClockcompares calendar readings. - Serialisable.
JSON.stringify/ template strings give the ISO form (DateOnly"2026-08-12",Time"09:05:30.123",YearAndMonth"2026-08",DateTime"2026-08-12T15:30:45.123+02:00",Period"P1Y2M3D",Duration"PT1H30M"), and each type'sfromIso8601reads it back; single fields serialise as plain numbers (Monthone-based). - Year 0 is 1 BC.
formatprints0000;formatLocaleshows the era (Jan 1, 1 BC) rather than a bare1.isoWeek().yearcan be-1for the first days of year 0, so it is a plain number.
Usage
import {
DateOnly, DateTime, DateTimeFormatter, DayOfWeek, Duration, Instant, InstantFormatter, Period, Time,
TimeInputFormat, Timezone, YearAndMonth,
} from '@luwiostack/datetime'
const brussels = Timezone.new({ name: 'Europe/Brussels' })
// DateTime — local (wall time in a zone) vs absolute (an instant) are separate constructors.
const dt = DateTime.fromLocalIso('2026-08-12T15:30:45.123', brussels) // seconds optional, ≤ 3 ms digits
DateTime.fromIso8601('2026-08-12T13:30:45.123Z') // absolute → UTC
DateTime.fromIso8601('2026-08-12T15:30:45.123+02:00', brussels) // same instant, on Brussels' clock
DateTime.fromIso8601('2026-08-12T15:30:45.123+02:00') // no zone → DST-free fixed-offset zone
DateTime.fromEpochMilliseconds(1786000000000, brussels) // whole epoch ms (zone required)
DateTime.now(brussels) // current instant in a zone
DateTime.fromLocalIso('2026-03-29T02:30', brussels, { disambiguation: 'later' }) // DST gap: choose a policy
dt.offset.inMinutes() // 120 (DST-aware, via @luwiostack/timezone)
dt.toIso8601() // '2026-08-12T15:30:45.123+02:00'
dt.toIso8601Utc() // '2026-08-12T13:30:45.123Z'
dt.inTimezone(Timezone.new({ name: 'America/New_York' })) // same instant, another zone's wall clock
// Compare, move, measure
dt.isBefore(other); dt.isSameInstant(other); dt.equals(other); dt.compareWallClock(other)
dt.isSameOffset(Timezone.fromOffset(120)) // does that zone show the same offset at dt's instant?
dt.add(Period.days(5)); dt.subtract(Period.months(1)) // calendar time: same wall clock, even across DST
// (a gap/overlap resolves 'compatible', like Temporal; { disambiguation } overrides)
dt.add(Duration.hours(2)) // exact elapsed time
dt.until(other) // signed exact Duration (hours by default); dt.add(dt.until(x)) is x
dt.until(other, { largestUnit: 'minutes' }) // 'seconds' | 'milliseconds' too
dt.startOfDay(); dt.endOfDay() // DST-safe bounds of the calendar day (23:59:59.999 on 9999-12-31)
dt.nextTransition(); dt.previousTransition() // DST changes; { horizonDays } to widen/narrow the search (≤ 100 years)
// DateOnly — a calendar day, years 0–9999, no library behind it
const date = DateOnly.of(2026, 8, 12) // or DateOnly.from(Year, Month, Day); YearAndMonth.of(2026, 8)
date.add(Period.months(2)).toIso8601() // '2026-10-12' (months clamp: 31 Jan + 1 month = 28/29 Feb)
date.until(DateOnly.of(2027, 1, 1)) // 142 — a signed number of days (since() is the reverse)
a.toDateOnly().until(b.toDateOnly()) // calendar days between two DateTimes
date.isoWeek() // { year: 2026, week: 33 }
date.startOfWeek(DayOfWeek.fromIso8601(1)) // the Monday of that week
DateOnly.fromIso8601('2026-08-12') // parses; a malformed string or impossible date (2026-02-30) throws
DateOnly.tryFromIso8601('nope') // null instead of throwing
// Time
Time.of(23, 30).add(Duration.hours(1)) // 00:30 — wraps at midnight (a Duration; a Period doesn't compile)
Time.fromIso8601('09:05:30.123') // also 'HH:mm' / 'HH:mm:ss'; the inverse of toIso8601()
Time.fromFormat('09:05', TimeInputFormat.HH_MM) // exactly one shape: 'HH:mm' (also HH_MM_SS, HH_MM_SS_SSS)
// Rendering lives in formatters, not on the objects (locale-free tokens + Intl):
DateTimeFormatter.format(dt, 'yyyy-MM-dd HH:mm:ss') // '2026-08-12 15:30:45'
DateTimeFormatter.format(dt, "dd 'of' MM") // quoted text is literal → '12 of 08'
DateTimeFormatter.format(dt, 'dd MMM') // throws InvalidPattern — month names are locale data: use formatLocale
DateTimeFormatter.formatLocale(dt, new Intl.Locale('nl')) // '12 aug 2026, 15:30:45' — exact text depends on the ICU versionCalendar and clock fields
The aggregates are made of small validated objects, each useful on its own: Year (0–9999,
isLeap()), Month (one-based everywhere: Month.fromOneBased(8), asInt() → 8; the JavaScript
Date convention only by name: fromZeroBased, asZeroBasedInt), Day (1–31), DayOfWeek (ISO:
Monday = 1; DayOfWeekIndex.ZERO_BASED for Monday = 0; isWeekend(), next()), YearAndMonth
(daysInMonth(), firstWeekdayOfMonth(), …), and Hour, Minute, Second, Millisecond. Each
has a factory — from (fromOneBased / fromZeroBased for Month, fromIso8601 /
fromZeroBased too for DayOfWeek, of for the plain-number aggregates) — with a try* twin,
asInt() and isSame, and serialises as a plain number. All but DayOfWeek also have isBefore /
isAfter; weekdays wrap around, so DayOfWeek steps with next() / previous() instead.
Year.from(2024).isLeap() // true
YearAndMonth.of(2026, 2).daysInMonth() // 28
DateOnly.of(2026, 8, 12).dayOfWeek.isWeekday() // true
Time.fromMilliseconds(45_296_789).toIso8601() // '12:34:56.789' — the inverse of toMilliseconds()Relative time
DateAgo / DateToBe (two DateOnlys, whole days) and TimeAgo / TimeToBe (two moments — each a
DateTime or an Instant — down to the second) hold a gap relative to a point in time you supply;
there is no hidden "now". Their formatters bucket the gap — buckets modelled on moment.js's fromNow
table, though counts are whole units completed rather than rounded, and 10–44 s reads "x seconds" — into a
translation token — a key plus, for plurals, placeholders.x — for your i18n layer, never a
finished sentence.
const ago = DateAgo.from(DateOnly.of(2026, 8, 1), DateOnly.of(2026, 9, 11))
ago.daysAgo() // 41
DateAgoFormatter.format(ago) // { key: 'a_month_ago' }
TimeToBeFormatter.format(TimeToBe.from(Instant.fromEpochMilliseconds(7_200_000), Instant.fromEpochMilliseconds(0)))
// { key: 'in_x_hours', placeholders: { x: '2' } }Formatters
Objects don't render themselves. Each has a static formatter with format(value, pattern) —
locale-free numeric tokens (yyyy yy MM M dd d HH H mm m ss s SSS, quoted text is literal) — and/or
formatLocale(value, locale, options?) via Intl:
| Formatter | format | formatLocale |
|---|---|---|
| DateTimeFormatter, DateOnlyFormatter, TimeFormatter, YearAndMonthFormatter | ✓ | ✓ |
| InstantFormatter (takes the zone to read the instant in) | ✓ | ✓ |
| MonthFormatter, DayOfWeekFormatter (a name is locale data) | — | ✓ |
| DateAgoFormatter, DateToBeFormatter, TimeAgoFormatter, TimeToBeFormatter | a token | — |
| DurationFormatter (1 hr, 30 min, or digital 1:30:00), PeriodFormatter (2 years, 3 months) | — | ✓ |
| OffsetFormatter (re-exported from @luwiostack/timezone) | ✓ ('extended' +02:00, 'basic' +0200, 'short' +2) | — |
| TimezoneFormatter (re-exported from @luwiostack/timezone): abbreviation(zone, locale?, at?), displayName(zone, locale?, { style?, at? }) | — | — |
A known pattern letter in an unsupported length (MMM, ddd) throws InvalidPattern.
Dates are always shown in the Gregorian calendar, whatever the locale's own (Persian in fa,
Buddhist in th, or a -u-ca- extension): the locale picks the language and digits, not the
calendar. DurationFormatter and PeriodFormatter use Intl.DurationFormat where the runtime has it
and an equivalent fallback where it doesn't — the same text, digits, signs and separators (digital
is 0:00:05,02 in nl, 0.00.05,02 in fi); a period too large for Intl.DurationFormat uses the
fallback too.
Instant
One absolute moment with no zone — epoch milliseconds (years 0–9999 in UTC). Use it for things that happened: it has no wall-clock fields, so a DST gap or overlap can never occur.
const at = Instant.fromIso8601('2026-08-12T13:30:45.123Z') // needs a Z or an offset
at.toDateTime(brussels).toIso8601() // '2026-08-12T15:30:45.123+02:00' — the zone is explicit
at.add(Duration.hours(24)); at.until(other) // exact arithmetic; a Period needs a zone
InstantFormatter.format(at, brussels, 'yyyy-MM-dd HH:mm') // '2026-08-12 15:30'What to store: an Instant for things that happened; wall time + zone name for a future event that
follows local time (resolve with DateTime.fromLocalIso, so a DST-rule change moves the instant, not the
intent); and for user input, convert once at the boundary with a disambiguation.
Period and Duration
Two kinds of "amount of time", kept apart so the wrong one doesn't compile:
Period— calendar time:Period.of({ years, months, days }),Period.months(1). It has no fixed length (a month is 28–31 days); years and months move first and clamp the day (31 Jan + 1 month = 28/29 Feb), then days. Taken byDateOnly.add/subtractandDateTime.add/subtract.Duration— exact elapsed time:Duration.of({ hours, minutes, seconds, milliseconds }),Duration.hours(2),Duration.ofMilliseconds(ms). Always converts exactly (inMilliseconds(),inMinutes(), …). Taken byTime.add/subtractandDateTime.add/subtract; returned byDateTime.until/sinceandInstant.until/since. (DateOnly.until/sincereturn a plain number of days — the only calendar unit with a fixed length.)
Every unit of both is a whole (safe) integer, negatives allowed. Render them with
DurationFormatter.formatLocale(d, locale, { style? }) — 1 hr, 30 min (short), 1 hour, 30 minutes
(long), 1h 30m (narrow) or 1:30:00 (digital) — and PeriodFormatter.formatLocale(p, locale) —
2 years, 3 months. Both use the platform's Intl.DurationFormat, with an equivalent fallback where it's
missing.
Errors
Everything this package throws on purpose extends DateTimeError, and error.name is the concrete
class: InvalidDateTime, InvalidDate, InvalidInstant, InvalidTimeFormat, InvalidPeriod,
InvalidDuration, InvalidPattern, the field errors (InvalidYear, InvalidMonth, InvalidDay,
InvalidDayOfWeek, InvalidHour, InvalidMinute, InvalidSecond, InvalidMillisecond) and the
relative-time ones (InvalidDateAgo, InvalidDateToBe, InvalidTimeAgo, InvalidTimeToBe). The
re-exported timezone errors (InvalidOffsetError, InvalidTimezoneError) extend TimezoneError
instead — timezone is the leaf and cannot depend on this package, so catch both families if you need to.
Every fallible factory has a try* twin built on the exported attempt(fn): it returns null for a
DateTimeError and rethrows anything else (a bug). Packages built on this one use it for their own
try* factories.
Error messages quote at most 64 characters of a rejected input, followed by its length, so a megabyte of
hostile input never becomes a megabyte of log. The exported previewInput(s) does the same for your own
messages (@luwiostack/schedule and @luwiostack/age use it).
Types
Type-only exports for your own signatures: Disambiguation ('reject' | 'earlier' | 'later' |
'compatible'), PeriodParts / DurationParts (what Period.of / Duration.of take), the relative-time
tokens IDateAgoFormat / IDateToBeFormat / ITimeAgoFormat / ITimeToBeFormat,
Iso8601WeekdayNumbers / ZeroBasedWeekdayNumbers, DurationStyle, and the re-exported OffsetFormat.
Related packages
These build on datetime (it never depends on them), and their errors extend DateTimeError too:
@luwiostack/schedule—TimeSlotandTimeSchedule: spans of a day and timetables.@luwiostack/age—DayOfBirthandYearsOfAge: completed age from a birth date.@luwiostack/clock— see below.
Clocks & React
An injectable "now" (SystemClock / TimezoneAwareClock / MockClock, each giving now(),
instant(), today() and time()) and the React hooks
(useNow / useToday / useClock) live in @luwiostack/clock, built on
DateTime.now. This package stays React-free.
Testing
pnpm test runs the suite once; pnpm test:tz runs it under TZ=UTC, Pacific/Apia and
America/Los_Angeles. It includes seeded property tests (ISO round-trips, until/add inversion,
ordering) and a compile-time check that every value object is nominally typed.
Temporal-readiness
DateTime's zone-aware operations go through an internal engine port (src/engine), the only place
a date library is imported. Today it's backed by luxon; the domain
value objects already mirror the TC39 Temporal shape (DateOnly ≈
Temporal.PlainDate, Time ≈ Temporal.PlainTime, DateTime ≈ Temporal.ZonedDateTime,
YearAndMonth ≈ Temporal.PlainYearMonth, Period + Duration ≈ Temporal.Duration). Moving to Temporal is a
rewrite of that one folder — this public API doesn't change — and will happen once Temporal is fully
supported everywhere the package runs; until then luxon stays.
