@c9up/chronos 0.1.15 → 0.1.17

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (74) hide show
  1. package/README.md +136 -16
  2. package/dist/DateTime.d.ts +209 -8
  3. package/dist/DateTime.d.ts.map +1 -1
  4. package/dist/DateTime.js +815 -116
  5. package/dist/DateTime.js.map +1 -1
  6. package/dist/Duration.d.ts +37 -20
  7. package/dist/Duration.d.ts.map +1 -1
  8. package/dist/Duration.js +287 -120
  9. package/dist/Duration.js.map +1 -1
  10. package/dist/Interval.d.ts +50 -7
  11. package/dist/Interval.d.ts.map +1 -1
  12. package/dist/Interval.js +142 -29
  13. package/dist/Interval.js.map +1 -1
  14. package/dist/atlas.d.ts +11 -15
  15. package/dist/atlas.d.ts.map +1 -1
  16. package/dist/atlas.js +22 -17
  17. package/dist/atlas.js.map +1 -1
  18. package/dist/format.d.ts +47 -0
  19. package/dist/format.d.ts.map +1 -0
  20. package/dist/format.js +387 -0
  21. package/dist/format.js.map +1 -0
  22. package/dist/holidays.d.ts +43 -0
  23. package/dist/holidays.d.ts.map +1 -0
  24. package/dist/holidays.js +102 -0
  25. package/dist/holidays.js.map +1 -0
  26. package/dist/index.d.ts +8 -6
  27. package/dist/index.d.ts.map +1 -1
  28. package/dist/index.js +4 -3
  29. package/dist/index.js.map +1 -1
  30. package/dist/native/generated.d.ts +11 -2
  31. package/dist/native/generated.d.ts.map +1 -1
  32. package/dist/native.d.ts.map +1 -1
  33. package/dist/native.js +5 -2
  34. package/dist/native.js.map +1 -1
  35. package/dist/parse.d.ts +59 -0
  36. package/dist/parse.d.ts.map +1 -0
  37. package/dist/parse.js +404 -0
  38. package/dist/parse.js.map +1 -0
  39. package/dist/rrule.d.ts +34 -2
  40. package/dist/rrule.d.ts.map +1 -1
  41. package/dist/rrule.js +156 -32
  42. package/dist/rrule.js.map +1 -1
  43. package/index.darwin-arm64.node +0 -0
  44. package/index.darwin-x64.node +0 -0
  45. package/index.linux-arm64-gnu.node +0 -0
  46. package/index.linux-x64-gnu.node +0 -0
  47. package/index.win32-x64-msvc.node +0 -0
  48. package/package.json +2 -3
  49. package/src/DateTime.ts +1089 -124
  50. package/src/Duration.ts +318 -139
  51. package/src/Interval.ts +160 -53
  52. package/src/atlas.ts +23 -17
  53. package/src/format.ts +449 -0
  54. package/src/holidays.ts +161 -0
  55. package/src/index.ts +35 -7
  56. package/src/native/generated.ts +27 -2
  57. package/src/native.ts +7 -3
  58. package/src/parse.ts +559 -0
  59. package/src/rrule.ts +229 -38
  60. package/wasm/chronos_engine_wasm.d.ts +13 -4
  61. package/wasm/chronos_engine_wasm.js +87 -16
  62. package/wasm/chronos_engine_wasm_bg.wasm +0 -0
  63. package/wasm/chronos_engine_wasm_bg.wasm.d.ts +5 -2
  64. package/dist/utils.d.ts +0 -15
  65. package/dist/utils.d.ts.map +0 -1
  66. package/dist/utils.js +0 -17
  67. package/dist/utils.js.map +0 -1
  68. package/scripts/build-napi-types.mjs +0 -69
  69. package/scripts/clean-wasm-pack-meta.mjs +0 -32
  70. package/scripts/copy-napi.mjs +0 -56
  71. package/scripts/generate-napi-types.mjs +0 -156
  72. package/scripts/verify-napi.mjs +0 -46
  73. package/scripts/verify-wasm.mjs +0 -55
  74. package/src/utils.ts +0 -17
package/src/DateTime.ts CHANGED
@@ -10,8 +10,28 @@
10
10
  *
11
11
  * @implements Epic 36 — Chronos
12
12
  */
13
+ import {
14
+ Duration,
15
+ type DurationObject,
16
+ type DurationUnit,
17
+ } from "./Duration.js";
18
+ import { formatLuxon } from "./format.js";
13
19
  import { nativeChronos } from "./native.js";
14
- import { normalizeIso } from "./utils.js";
20
+ import {
21
+ type CalendarDay,
22
+ dayOfMs,
23
+ daysInYearOf,
24
+ dayToIsoWeek,
25
+ dayToOrdinal,
26
+ isoWeekday,
27
+ isoWeeksInYear,
28
+ isoWeekToDay,
29
+ ordinalToDay,
30
+ type ParsedFields,
31
+ type ParsedText,
32
+ parseWithFormat,
33
+ utcDayMs,
34
+ } from "./parse.js";
15
35
 
16
36
  export type DateUnit =
17
37
  | "second"
@@ -110,53 +130,514 @@ function daysInMonthOf(year: number, month: number): number {
110
130
  }
111
131
 
112
132
  /**
113
- * Refuse a calendar date that does not exist, instead of sliding to the next
114
- * one that does.
115
- *
116
- * `new Date('2026-02-30')` answers 2026-03-02: the overflow semantics are right
117
- * for arithmetic — adding a month to January 31st has to land somewhere — and
118
- * wrong for reading input, where the same slide turns a typo into a fact. The
119
- * inconsistency was the dangerous part: '2026-13-45' threw while '2026-02-30'
120
- * came back as a date, so a caller wrapping this in try/catch had covered the
121
- * loud half and left the half that writes something false to the database.
133
+ * The only strings a `DateTime` reads: ISO 8601 calendar dates, optionally with
134
+ * a time (`T` or, as SQL writes it, a space) and an offset (`Z`, `±HH`,
135
+ * `±HHMM`, `±HH:MM`). Anything else is refused: V8's fallback parser turns
136
+ * `"1"` or `"foo 2026"` into a date, and reads an offset-less time in the
137
+ * HOST zone, so the same text named a different instant on every machine.
138
+ */
139
+ const ISO_8601 =
140
+ /^(\d{4})-(\d{2})-(\d{2})(?:[Tt ](\d{2}):(\d{2})(?::(\d{2})(?:[.,](\d{1,9}))?)?(?:\s?([Zz])|\s?([+-])(\d{2})(?::?(\d{2}))?)?)?$/;
141
+
142
+ /** First and last instants a value may hold: what a four-digit ISO year writes. */
143
+ const MIN_MS = -62_167_219_200_000; // 0000-01-01T00:00:00.000Z
144
+ const MAX_MS = 253_402_300_799_999; // 9999-12-31T23:59:59.999Z
145
+
146
+ interface WallClock {
147
+ year: number;
148
+ month: number;
149
+ day: number;
150
+ hour: number;
151
+ minute: number;
152
+ second: number;
153
+ millisecond: number;
154
+ }
155
+
156
+ /**
157
+ * Refuse a wall-clock value that does not exist, instead of sliding to the
158
+ * next one that does.
122
159
  *
123
- * `fromObject` has always refused the same input; this is that check on the
124
- * door that was missing it. Only the written date is examined, never the
125
- * instant it resolves to, so an offset that legitimately moves the UTC day
126
- * ('2026-08-10T23:00:00-05:00' → the 11th) is untouched.
160
+ * `new Date('2026-02-30')` answers 2026-03-02 and `Date.UTC(…, 10, 90)` reads
161
+ * minute 90 as 11:30: the overflow semantics are right for arithmetic — adding
162
+ * a month to January 31st has to land somewhere — and wrong for reading input,
163
+ * where the same slide turns a typo into a fact. Only the written value is
164
+ * examined, never the instant it resolves to, so an offset that legitimately
165
+ * moves the UTC day ('2026-08-10T23:00:00-05:00' → the 11th) is untouched.
166
+ */
167
+ function assertWallClock(c: WallClock, raw: string): void {
168
+ const integer = (unit: string, value: number, min: number, max: number) => {
169
+ if (!Number.isInteger(value) || value < min || value > max) {
170
+ throw new RangeError(
171
+ `Invalid date '${raw}': ${unit} ${String(value)} is out of range (${min}-${max}).`,
172
+ );
173
+ }
174
+ };
175
+ integer("year", c.year, 0, 9999);
176
+ if (!Number.isInteger(c.month) || c.month < 1 || c.month > 12) {
177
+ throw new RangeError(
178
+ `Invalid date '${raw}': there is no month ${String(c.month)}.`,
179
+ );
180
+ }
181
+ const lastDay = daysInMonthOf(c.year, c.month);
182
+ if (!Number.isInteger(c.day) || c.day < 1 || c.day > lastDay) {
183
+ throw new RangeError(
184
+ `Invalid date '${raw}': ${MONTH_NAMES[c.month - 1]} ${c.year} has ${lastDay} days, so there is no day ${String(c.day)}.`,
185
+ );
186
+ }
187
+ integer("hour", c.hour, 0, 23);
188
+ integer("minute", c.minute, 0, 59);
189
+ integer("second", c.second, 0, 59);
190
+ integer("millisecond", c.millisecond, 0, 999);
191
+ }
192
+
193
+ /** Epoch milliseconds of a UTC wall clock; years 0-99 stay literal (Date.UTC maps them to 19xx). */
194
+ function utcMs(c: WallClock): number {
195
+ const d = new Date(0);
196
+ d.setUTCFullYear(c.year, c.month - 1, c.day);
197
+ d.setUTCHours(c.hour, c.minute, c.second, c.millisecond);
198
+ return d.getTime();
199
+ }
200
+
201
+ const pad = (n: number, width = 2): string => String(n).padStart(width, "0");
202
+
203
+ /** Epoch milliseconds of a wall clock read in `zone`. */
204
+ function wallClockMs(c: WallClock, zone: string): number {
205
+ if (zone === "UTC") return utcMs(c);
206
+ const naive = `${pad(c.year, 4)}-${pad(c.month)}-${pad(c.day)}T${pad(c.hour)}:${pad(c.minute)}:${pad(c.second)}`;
207
+ return Date.parse(nativeChronos().fromLocal(naive, zone)) + c.millisecond;
208
+ }
209
+
210
+ /** The canonical UTC ISO string of an instant, refusing what chronos cannot hold. */
211
+ function isoOfMs(ms: number, input: () => string): string {
212
+ if (!Number.isFinite(ms)) throw new RangeError(`Invalid date ${input()}`);
213
+ if (ms < MIN_MS || ms > MAX_MS) {
214
+ throw new RangeError(
215
+ `Date ${input()} is out of range: years are limited to 0000-9999.`,
216
+ );
217
+ }
218
+ return new Date(ms).toISOString();
219
+ }
220
+
221
+ /**
222
+ * Fill the units a `fromFormat` text left out, as Luxon's `fromObject` does:
223
+ * the units larger than the largest one written come from `now`, the smaller
224
+ * ones take their minimum. A text naming a week (`kkkk`, `W`) or only a
225
+ * weekday is read on the ISO week calendar, one naming an ordinal (`o`) on the
226
+ * ordinal calendar. Every unit is range-checked; hour 24 is accepted at
227
+ * 24:00:00.000 and is midnight of the next day, as Luxon reads it.
127
228
  */
128
- const CALENDAR_DATE = /^(\d{4})-(\d{2})-(\d{2})(?=$|[T ])/;
129
-
130
- function assertCalendarDateExists(raw: string): void {
131
- const match = CALENDAR_DATE.exec(raw);
132
- // Anything else — RFC 2822, a bare year, a basic-format string — is left to
133
- // `Date`, which already refuses what it cannot read.
134
- if (!match) return;
135
- const year = Number(match[1]);
136
- const month = Number(match[2]);
137
- const day = Number(match[3]);
138
- if (month < 1 || month > 12) {
139
- throw new Error(`Invalid date '${raw}': there is no month ${month}.`);
140
- }
141
- const lastDay = daysInMonthOf(year, month);
142
- if (day < 1 || day > lastDay) {
229
+ function resolveParsedFields(
230
+ f: ParsedFields,
231
+ now: WallClock,
232
+ raw: string,
233
+ ): WallClock {
234
+ const hasOrdinal = f.ordinal !== undefined;
235
+ const hasMonthDay = f.month !== undefined || f.day !== undefined;
236
+ const hasGregorian = f.year !== undefined || hasMonthDay;
237
+ const weekDefined = f.weekYear !== undefined || f.weekNumber !== undefined;
238
+ if ((hasGregorian || hasOrdinal) && weekDefined) {
143
239
  throw new Error(
144
- `Invalid date '${raw}': ${MONTH_NAMES[month - 1]} ${year} has ${lastDay} days, so there is no day ${day}.`,
240
+ "Can't mix weekYear/weekNumber units with year/month/day or ordinals",
241
+ );
242
+ }
243
+ if (hasMonthDay && hasOrdinal) {
244
+ throw new Error("Can't mix ordinal dates with month/day");
245
+ }
246
+ let found = false;
247
+ const take = (given: number | undefined, current: number, min: number) => {
248
+ if (given !== undefined) {
249
+ found = true;
250
+ return given;
251
+ }
252
+ return found ? min : current;
253
+ };
254
+ const range = (unit: string, value: number, min: number, max: number) => {
255
+ if (!Number.isInteger(value) || value < min || value > max) {
256
+ throw new RangeError(
257
+ `Invalid date '${raw}': ${unit} ${String(value)} is out of range (${min}-${max}).`,
258
+ );
259
+ }
260
+ };
261
+ const nowDay: CalendarDay = {
262
+ year: now.year,
263
+ month: now.month,
264
+ day: now.day,
265
+ };
266
+ let day: CalendarDay;
267
+ if (weekDefined || (f.weekday !== undefined && !hasGregorian)) {
268
+ const nowWeek = dayToIsoWeek(nowDay);
269
+ const weekYear = take(f.weekYear, nowWeek.weekYear, 1);
270
+ const weekNumber = take(f.weekNumber, nowWeek.weekNumber, 1);
271
+ const weekday = take(f.weekday, nowWeek.weekday, 1);
272
+ range("weekYear", weekYear, 0, 9999);
273
+ range("weekNumber", weekNumber, 1, isoWeeksInYear(weekYear));
274
+ range("weekday", weekday, 1, 7);
275
+ day = isoWeekToDay(weekYear, weekNumber, weekday);
276
+ } else if (hasOrdinal) {
277
+ const year = take(f.year, now.year, 1);
278
+ const ordinal = take(f.ordinal, dayToOrdinal(nowDay), 1);
279
+ range("year", year, 0, 9999);
280
+ range("ordinal", ordinal, 1, daysInYearOf(year));
281
+ day = ordinalToDay(year, ordinal);
282
+ } else {
283
+ day = {
284
+ year: take(f.year, now.year, 1),
285
+ month: take(f.month, now.month, 1),
286
+ day: take(f.day, now.day, 1),
287
+ };
288
+ }
289
+ const clock: WallClock = {
290
+ ...day,
291
+ hour: take(f.hour, now.hour, 0),
292
+ minute: take(f.minute, now.minute, 0),
293
+ second: take(f.second, now.second, 0),
294
+ millisecond: take(f.millisecond, now.millisecond, 0),
295
+ };
296
+ const endOfDay =
297
+ clock.hour === 24 &&
298
+ clock.minute === 0 &&
299
+ clock.second === 0 &&
300
+ clock.millisecond === 0;
301
+ assertWallClock(endOfDay ? { ...clock, hour: 0 } : clock, raw);
302
+ const out = endOfDay
303
+ ? {
304
+ ...clock,
305
+ ...dayOfMs(utcDayMs(clock.year, clock.month, clock.day + 1)),
306
+ hour: 0,
307
+ }
308
+ : clock;
309
+ assertWallClock(out, raw);
310
+ if (
311
+ f.weekday !== undefined &&
312
+ hasGregorian &&
313
+ isoWeekday(out) !== f.weekday
314
+ ) {
315
+ throw new RangeError(
316
+ `Invalid date '${raw}': weekday ${f.weekday} does not fall on ${pad(out.year, 4)}-${pad(out.month)}-${pad(out.day)}.`,
145
317
  );
146
318
  }
319
+ return out;
320
+ }
321
+
322
+ /** Now as a wall clock in `zone`, or at a fixed `offset` (minutes) when the text gave one. */
323
+ function nowWallClock(zone: string, offset: number | undefined): WallClock {
324
+ if (offset === undefined) {
325
+ const { year, month, day, hour, minute, second, millisecond } =
326
+ DateTime.now(zone).calendar;
327
+ return { year, month, day, hour, minute, second, millisecond };
328
+ }
329
+ const d = new Date(Date.now() + offset * 60_000);
330
+ return {
331
+ year: d.getUTCFullYear(),
332
+ month: d.getUTCMonth() + 1,
333
+ day: d.getUTCDate(),
334
+ hour: d.getUTCHours(),
335
+ minute: d.getUTCMinutes(),
336
+ second: d.getUTCSeconds(),
337
+ millisecond: d.getUTCMilliseconds(),
338
+ };
339
+ }
340
+
341
+ /**
342
+ * The instant of a parsed wall clock. An offset alone fixes it. A zone and an
343
+ * offset together: the offset settles the hour a zone repeats when its clocks
344
+ * go back, as long as the zone has that offset then; otherwise the zone wins.
345
+ */
346
+ function instantOfParsed(
347
+ c: WallClock,
348
+ parsed: ParsedText,
349
+ wallZone: string,
350
+ ): number {
351
+ if (parsed.offset !== undefined) {
352
+ const atOffset = utcMs(c) - parsed.offset * 60_000;
353
+ if (parsed.zone === undefined) return atOffset;
354
+ const zoneOffset =
355
+ parsed.zone === "UTC"
356
+ ? 0
357
+ : nativeChronos().zoneOffset(
358
+ isoOfMs(atOffset, () => `'${parsed.zone}'`),
359
+ parsed.zone,
360
+ );
361
+ if (zoneOffset === parsed.offset) return atOffset;
362
+ }
363
+ return wallClockMs(c, wallZone);
364
+ }
365
+
366
+ /** Read an ISO 8601 string; an offset-less one is a wall clock in `zone`. */
367
+ function parseIso(raw: string, zone: string): string {
368
+ const m = ISO_8601.exec(raw);
369
+ if (!m) {
370
+ throw new RangeError(
371
+ `Invalid date '${raw}': expected ISO 8601 (YYYY-MM-DD, optionally with THH:mm[:ss[.SSS]] and an offset).`,
372
+ );
373
+ }
374
+ const c: WallClock = {
375
+ year: Number(m[1]),
376
+ month: Number(m[2]),
377
+ day: Number(m[3]),
378
+ hour: Number(m[4] ?? 0),
379
+ minute: Number(m[5] ?? 0),
380
+ second: Number(m[6] ?? 0),
381
+ millisecond: Math.floor(Number(`0.${m[7] ?? "0"}`) * 1000),
382
+ };
383
+ assertWallClock(c, raw);
384
+ let ms: number;
385
+ if (m[8] !== undefined) {
386
+ ms = utcMs(c);
387
+ } else if (m[9] !== undefined) {
388
+ const hours = Number(m[10]);
389
+ const minutes = Number(m[11] ?? 0);
390
+ if (hours > 23 || minutes > 59) {
391
+ throw new RangeError(
392
+ `Invalid date '${raw}': the offset is out of range.`,
393
+ );
394
+ }
395
+ const sign = m[9] === "-" ? -1 : 1;
396
+ ms = utcMs(c) - sign * (hours * 60 + minutes) * 60_000;
397
+ } else {
398
+ ms = wallClockMs(c, zone);
399
+ }
400
+ return isoOfMs(ms, () => `'${raw}'`);
147
401
  }
148
402
 
149
- function toIso(value: DateInput): string {
403
+ function toIso(value: DateInput, zone = "UTC"): string {
150
404
  if (value instanceof DateTime) return value.toISO();
151
- if (value instanceof Date) return normalizeIso(value.toISOString());
152
- if (typeof value === "string") assertCalendarDateExists(value);
153
- return normalizeIso(new Date(value).toISOString());
405
+ if (value instanceof Date) {
406
+ return isoOfMs(value.getTime(), () => "(JS Date)");
407
+ }
408
+ if (typeof value !== "string") {
409
+ throw new TypeError(
410
+ `Invalid date input: expected a string, a Date or a DateTime, got ${typeof value}`,
411
+ );
412
+ }
413
+ return parseIso(value, zone);
154
414
  }
155
415
 
156
416
  function toMs(value: DateInput): number {
157
417
  return new Date(toIso(value)).getTime();
158
418
  }
159
419
 
420
+ const CASUAL_UNIT_MS: Readonly<Record<string, number>> = {
421
+ second: 1_000,
422
+ minute: 60_000,
423
+ hour: 3_600_000,
424
+ day: 86_400_000,
425
+ week: 604_800_000,
426
+ month: 30 * 86_400_000,
427
+ year: 365 * 86_400_000,
428
+ };
429
+
430
+ /** Milliseconds in one unit on Luxon's casual matrix; throws on an unknown unit. */
431
+ function casualUnitMs(unit: string): number {
432
+ const singular = unit.endsWith("s") ? unit.slice(0, -1) : unit;
433
+ const ms = Object.hasOwn(CASUAL_UNIT_MS, singular)
434
+ ? CASUAL_UNIT_MS[singular]
435
+ : undefined;
436
+ if (ms === undefined) throw new Error(`Unsupported unit: ${unit}`);
437
+ return ms;
438
+ }
439
+
440
+ const DIFF_ORDER: readonly DurationUnit[] = [
441
+ "years",
442
+ "months",
443
+ "weeks",
444
+ "days",
445
+ "hours",
446
+ "minutes",
447
+ "seconds",
448
+ "milliseconds",
449
+ ];
450
+ const CALENDAR_UNITS: ReadonlySet<DurationUnit> = new Set([
451
+ "years",
452
+ "months",
453
+ "weeks",
454
+ "days",
455
+ ]);
456
+
457
+ /** A unit `toRelative` and `toRelativeCalendar` can count in. */
458
+ export type RelativeUnit =
459
+ | "years"
460
+ | "months"
461
+ | "weeks"
462
+ | "days"
463
+ | "hours"
464
+ | "minutes"
465
+ | "seconds";
466
+ export type RelativeUnitLike =
467
+ | RelativeUnit
468
+ | "year"
469
+ | "month"
470
+ | "week"
471
+ | "day"
472
+ | "hour"
473
+ | "minute"
474
+ | "second";
475
+ export type RelativeRounding = "trunc" | "expand" | "round" | "floor" | "ceil";
476
+
477
+ interface RelativeFormatOptions {
478
+ /** Compared against; now, in this value's zone, by default. */
479
+ base?: DateInput;
480
+ /** Overrides this value's locale. */
481
+ locale?: Intl.LocalesArgument;
482
+ style?: Intl.RelativeTimeFormatStyle;
483
+ /** Reaches the formatter; the engine may not honour it. */
484
+ numberingSystem?: string;
485
+ }
486
+
487
+ export interface ToRelativeOptions extends RelativeFormatOptions {
488
+ /** One unit, or the units to pick the largest non-zero one from. */
489
+ unit?: RelativeUnitLike | readonly RelativeUnitLike[];
490
+ /** Round the count (default), or keep two decimals. */
491
+ round?: boolean;
492
+ /** How the count is rounded; toward zero by default. */
493
+ rounding?: RelativeRounding;
494
+ /** Milliseconds added away from the base before counting. */
495
+ padding?: number;
496
+ }
497
+
498
+ export interface ToRelativeCalendarOptions extends RelativeFormatOptions {
499
+ unit?: RelativeUnitLike;
500
+ }
501
+
502
+ const RELATIVE_UNITS: readonly RelativeUnit[] = [
503
+ "years",
504
+ "months",
505
+ "weeks",
506
+ "days",
507
+ "hours",
508
+ "minutes",
509
+ "seconds",
510
+ ];
511
+ const TO_RELATIVE_UNITS: readonly RelativeUnit[] = [
512
+ "years",
513
+ "months",
514
+ "days",
515
+ "hours",
516
+ "minutes",
517
+ "seconds",
518
+ ];
519
+ const TO_RELATIVE_CALENDAR_UNITS: readonly RelativeUnit[] = [
520
+ "years",
521
+ "months",
522
+ "days",
523
+ ];
524
+ const BOUND_OF: Readonly<Record<RelativeUnit, BoundUnit>> = {
525
+ years: "year",
526
+ months: "month",
527
+ weeks: "week",
528
+ days: "day",
529
+ hours: "hour",
530
+ minutes: "minute",
531
+ seconds: "second",
532
+ };
533
+
534
+ function relativeUnitOf(unit: unknown): RelativeUnit {
535
+ const plural =
536
+ typeof unit === "string" && !unit.endsWith("s") ? `${unit}s` : unit;
537
+ const found = RELATIVE_UNITS.find((u) => u === plural);
538
+ if (found === undefined) {
539
+ throw new RangeError(`Unsupported relative unit: ${String(unit)}`);
540
+ }
541
+ return found;
542
+ }
543
+
544
+ /** Round to `digits` decimals the way the reference library's `roundTo` does. */
545
+ function roundTo(value: number, digits: number, rounding: unknown): number {
546
+ const factor = 10 ** digits;
547
+ switch (rounding) {
548
+ case "expand":
549
+ return value > 0
550
+ ? Math.ceil(value * factor) / factor
551
+ : Math.floor(value * factor) / factor;
552
+ case "trunc":
553
+ return Math.trunc(value * factor) / factor;
554
+ case "round":
555
+ return Math.round(value * factor) / factor;
556
+ case "floor":
557
+ return Math.floor(value * factor) / factor;
558
+ case "ceil":
559
+ return Math.ceil(value * factor) / factor;
560
+ default:
561
+ throw new RangeError(
562
+ `Value rounding ${String(rounding)} is out of range`,
563
+ );
564
+ }
565
+ }
566
+
567
+ /**
568
+ * The reference library's `diffRelative`: count `end - start` in the first
569
+ * unit (largest first) that reaches 1, or in the one unit asked for.
570
+ * `calendary` counts calendar boundaries crossed (yesterday is 1 day back at
571
+ * 23:59 as at 00:01) and rounds to the nearest; otherwise the count is the
572
+ * calendar-aware diff, truncated unless `rounding` says otherwise.
573
+ */
574
+ function diffRelative(
575
+ start: DateTime,
576
+ end: DateTime,
577
+ opts: RelativeFormatOptions & {
578
+ units: readonly RelativeUnit[];
579
+ unit: RelativeUnit | undefined;
580
+ calendary: boolean;
581
+ numeric: "always" | "auto";
582
+ round?: boolean;
583
+ rounding?: RelativeRounding;
584
+ },
585
+ ): string {
586
+ const round = opts.round ?? true;
587
+ const rounding = opts.rounding ?? "trunc";
588
+ // NAMED DEVIATION: the reference library prints English (en, en-US) from a
589
+ // hand-written table and every other locale through Intl. Every locale goes
590
+ // through Intl here, so en-US gets CLDR's own short and narrow forms
591
+ // ("2d ago" in narrow, where the table prints "2 days ago"); the long style,
592
+ // the default, reads the same.
593
+ const intlOptions: Intl.RelativeTimeFormatOptions & {
594
+ numberingSystem?: string;
595
+ } = {
596
+ numeric: opts.numeric,
597
+ style: opts.style ?? "long",
598
+ };
599
+ if (opts.numberingSystem !== undefined) {
600
+ intlOptions.numberingSystem = opts.numberingSystem;
601
+ }
602
+ const formatter = new Intl.RelativeTimeFormat(
603
+ opts.locale ?? end.locale,
604
+ intlOptions,
605
+ );
606
+ const format = (count: number, unit: RelativeUnit): string =>
607
+ formatter.format(
608
+ roundTo(
609
+ count,
610
+ round || opts.calendary ? 0 : 2,
611
+ opts.calendary ? "round" : rounding,
612
+ ),
613
+ unit,
614
+ );
615
+ const differ = (unit: RelativeUnit): number => {
616
+ if (opts.calendary) {
617
+ const bound = BOUND_OF[unit];
618
+ if (end.hasSame(start, bound)) return 0;
619
+ return end.startOf(bound).diff(start.startOf(bound), unit).as(unit);
620
+ }
621
+ return end.diff(start, unit).as(unit);
622
+ };
623
+
624
+ if (opts.unit !== undefined) return format(differ(opts.unit), opts.unit);
625
+ for (const unit of opts.units) {
626
+ const count = differ(unit);
627
+ if (Math.abs(count) >= 1) return format(count, unit);
628
+ }
629
+ const last = opts.units.at(-1);
630
+ if (last === undefined) throw new RangeError("No unit to count in");
631
+ return format(start.toMillis() > end.toMillis() ? -0 : 0, last);
632
+ }
633
+
634
+ function durationUnitOf(unit: string): DurationUnit {
635
+ const plural = unit.endsWith("s") ? unit : `${unit}s`;
636
+ const found = DIFF_ORDER.find((u) => u === plural);
637
+ if (found === undefined) throw new RangeError(`Unsupported unit: ${unit}`);
638
+ return found;
639
+ }
640
+
160
641
  function isCalendarUnit(unit: DateUnit): boolean {
161
642
  return (
162
643
  unit === "day" || unit === "week" || unit === "month" || unit === "year"
@@ -331,28 +812,116 @@ function rangesOverlap(
331
812
  : Math.max(na.start, nb.start) < Math.min(na.end, nb.end);
332
813
  }
333
814
 
815
+ // ─── Zone validation ─────────────────────────────────────────
816
+
817
+ /**
818
+ * Zones the engine has already accepted, exactly as it names them.
819
+ *
820
+ * Every derived value (`plus`, `startOf`, …) is built through the constructor
821
+ * with the zone of the value it came from, so without this each one would pay
822
+ * a native call to re-validate a zone that was checked on the way in. Only a
823
+ * name equal to the engine's canonical spelling is remembered: the set is then
824
+ * bounded by the tz database, whatever spellings a caller sends.
825
+ */
826
+ const acceptedZones = new Set<string>(["UTC"]);
827
+
828
+ /**
829
+ * Throw on a zone the tz database does not know — the one check behind every
830
+ * entry that takes a zone (`new DateTime(input, zone)`, `DateTime.now(zone)`,
831
+ * `setZone`), so all three refuse the same names with the same message.
832
+ */
833
+ function assertZone(zone: string): void {
834
+ if (acceptedZones.has(zone)) return;
835
+ const canonical = nativeChronos().validateTimezone(zone);
836
+ if (canonical === zone) acceptedZones.add(zone);
837
+ }
838
+
334
839
  // ─── DateTime class ──────────────────────────────────────────
335
840
 
336
841
  export class DateTime {
337
842
  #iso: string;
338
843
  #zone: string;
844
+ /** Locale for names in `toFormat` and for `toLocaleString`; en-US unless set. */
845
+ #locale = "en-US";
339
846
 
847
+ /**
848
+ * @throws on a zone the tz database does not know. An unknown zone used to
849
+ * be stored as given and break later, on the first offset or format.
850
+ */
340
851
  constructor(input: string | Date = new Date(), zone = "UTC") {
341
- this.#iso = toIso(input);
852
+ assertZone(zone);
853
+ this.#iso = toIso(input, zone);
342
854
  this.#zone = zone;
343
855
  }
344
856
 
345
857
  static from(input: DateInput): DateTime {
346
- if (input instanceof DateTime) return new DateTime(input.#iso, input.#zone);
858
+ if (input instanceof DateTime) return input.#derive(input.#iso);
347
859
  return new DateTime(toIso(input));
348
860
  }
861
+
862
+ /** A value derived from this one: same zone (unless given) and locale. */
863
+ #derive(input: string | Date, zone = this.#zone): DateTime {
864
+ const out = new DateTime(input, zone);
865
+ out.#locale = this.#locale;
866
+ return out;
867
+ }
868
+
869
+ /** Now, or the given wall clock, in the host's zone (Luxon's `DateTime.local`). */
870
+ static local(
871
+ year?: number,
872
+ month = 1,
873
+ day = 1,
874
+ hour = 0,
875
+ minute = 0,
876
+ second = 0,
877
+ millisecond = 0,
878
+ ): DateTime {
879
+ const zone = Intl.DateTimeFormat().resolvedOptions().timeZone;
880
+ if (year === undefined) return DateTime.now(zone);
881
+ return DateTime.fromObject(
882
+ { year, month, day, hour, minute, second, millisecond },
883
+ { zone },
884
+ );
885
+ }
886
+
887
+ /** Now, or the given wall clock, in UTC (Luxon's `DateTime.utc`). */
888
+ static utc(
889
+ year?: number,
890
+ month = 1,
891
+ day = 1,
892
+ hour = 0,
893
+ minute = 0,
894
+ second = 0,
895
+ millisecond = 0,
896
+ ): DateTime {
897
+ if (year === undefined) return DateTime.now();
898
+ return DateTime.fromObject({
899
+ year,
900
+ month,
901
+ day,
902
+ hour,
903
+ minute,
904
+ second,
905
+ millisecond,
906
+ });
907
+ }
349
908
  static now(zone?: string): DateTime {
350
909
  return new DateTime(new Date(), zone ?? "UTC");
351
910
  }
352
911
  static fromMillis(ms: number): DateTime {
912
+ if (typeof ms !== "number") {
913
+ throw new TypeError(`fromMillis expects a number, got ${typeof ms}`);
914
+ }
353
915
  return new DateTime(new Date(ms));
354
916
  }
355
917
  static fromSeconds(seconds: number): DateTime {
918
+ // Same guard as fromMillis: `seconds * 1000` would turn "12" into 12 s
919
+ // and null into the epoch.
920
+ if (typeof seconds !== "number") {
921
+ throw new TypeError(
922
+ `fromSeconds expects a number, got ${seconds === null ? "null" : typeof seconds}`,
923
+ );
924
+ }
356
925
  return new DateTime(new Date(seconds * 1000));
357
926
  }
358
927
  static fromUnix(seconds: number): DateTime {
@@ -362,44 +931,124 @@ export class DateTime {
362
931
  if (!Number.isFinite(date.getTime())) throw new Error("Invalid Date");
363
932
  return new DateTime(date);
364
933
  }
365
- static fromObject(obj: {
366
- year: number;
367
- month: number;
368
- day: number;
369
- hour?: number;
370
- minute?: number;
371
- second?: number;
372
- ms?: number;
373
- }): DateTime {
374
- if (obj.month < 1 || obj.month > 12)
375
- throw new Error(`Invalid month: ${obj.month}`);
376
- if (obj.day < 1 || obj.day > 31) throw new Error(`Invalid day: ${obj.day}`);
377
- const d = new Date(
378
- Date.UTC(
379
- obj.year,
380
- obj.month - 1,
381
- obj.day,
382
- obj.hour ?? 0,
383
- obj.minute ?? 0,
384
- obj.second ?? 0,
385
- obj.ms ?? 0,
386
- ),
934
+ /**
935
+ * Read an ISO 8601 string. An offset-less one is a wall clock in
936
+ * `options.zone` (UTC by default), and the result is in that zone.
937
+ */
938
+ static fromISO(text: string, options: { zone?: string } = {}): DateTime {
939
+ return new DateTime(text, options.zone ?? "UTC");
940
+ }
941
+
942
+ /**
943
+ * Build from calendar fields, read as a wall clock in `options.zone` (UTC by
944
+ * default). Every field is checked: an integer within its range (minute
945
+ * 0-59, …), and a year read literally (50 is year 0050, not 1950).
946
+ */
947
+ static fromObject(
948
+ obj: {
949
+ year: number;
950
+ month: number;
951
+ day: number;
952
+ hour?: number;
953
+ minute?: number;
954
+ second?: number;
955
+ millisecond?: number;
956
+ /** @deprecated spelled `millisecond`, as Luxon does. */
957
+ ms?: number;
958
+ },
959
+ options: { zone?: string } = {},
960
+ ): DateTime {
961
+ const zone = options.zone ?? "UTC";
962
+ assertZone(zone);
963
+ const c: WallClock = {
964
+ year: obj.year,
965
+ month: obj.month,
966
+ day: obj.day,
967
+ hour: obj.hour ?? 0,
968
+ minute: obj.minute ?? 0,
969
+ second: obj.second ?? 0,
970
+ millisecond: obj.millisecond ?? obj.ms ?? 0,
971
+ };
972
+ assertWallClock(c, JSON.stringify(obj));
973
+ return new DateTime(
974
+ isoOfMs(wallClockMs(c, zone), () => JSON.stringify(obj)),
975
+ zone,
387
976
  );
388
- if (d.getUTCMonth() !== obj.month - 1 || d.getUTCDate() !== obj.day) {
389
- throw new Error(`Invalid date object: ${JSON.stringify(obj)}`);
390
- }
391
- return new DateTime(d);
392
977
  }
393
978
  static fromRFC2822(input: string): DateTime {
394
979
  return new DateTime(nativeChronos().parseRfc2822(input));
395
980
  }
396
- static fromSQL(input: string): DateTime {
397
- return new DateTime(nativeChronos().parseSql(input));
981
+ /**
982
+ * Read a SQL literal: `YYYY-MM-DD`, or `YYYY-MM-DD HH:mm[:ss[.fff]]` with an
983
+ * optional offset (`+00`, `+02:00` — PostgreSQL's `timestamptz` text) or
984
+ * IANA zone. Without one, the value is a wall clock in `options.zone` (UTC
985
+ * by default), and the result is in that zone.
986
+ */
987
+ static fromSQL(input: string, options: { zone?: string } = {}): DateTime {
988
+ const zone = options.zone ?? "UTC";
989
+ assertZone(zone);
990
+ return new DateTime(
991
+ nativeChronos().parseSql(input, zone === "UTC" ? undefined : zone),
992
+ zone,
993
+ );
398
994
  }
399
995
  static fromHTTP(input: string): DateTime {
400
996
  return new DateTime(nativeChronos().parseHttp(input));
401
997
  }
402
998
 
999
+ /**
1000
+ * Read `text` written with Luxon's format tokens (`dd/MM/yyyy HH:mm`,
1001
+ * `dd LLL yyyy 'at' h:mm a`, `kkkk-'W'WW-c`, macros such as `D` or `f`), as
1002
+ * Luxon's `fromFormat`. Units the format leaves out are filled as Luxon
1003
+ * fills them: larger ones from now, smaller ones with their minimum
1004
+ * (`HH:mm` is today at that time, `MMMM` the 1st of that month this year).
1005
+ *
1006
+ * The wall clock is read in the zone the text names (`z`), else at the
1007
+ * offset it writes (`Z`, `ZZ`, `ZZZ`), else in `options.zone` (UTC by
1008
+ * default); the result is in `options.zone`. Names are matched in
1009
+ * `options.locale` (en-US by default), which the result keeps.
1010
+ *
1011
+ * Two deviations, named: text that does not match the format, or names a
1012
+ * date that does not exist, throws instead of returning an invalid value
1013
+ * (chronos has no invalid DateTime); and there is no `setZone` option, since
1014
+ * a chronos zone is an IANA name and an offset alone names none.
1015
+ */
1016
+ static fromFormat(
1017
+ text: string,
1018
+ format: string,
1019
+ options: { zone?: string; locale?: string } = {},
1020
+ ): DateTime {
1021
+ if (typeof text !== "string" || typeof format !== "string") {
1022
+ throw new TypeError("fromFormat requires an input string and a format");
1023
+ }
1024
+ const zone = options.zone ?? "UTC";
1025
+ assertZone(zone);
1026
+ const locale = options.locale ?? "en-US";
1027
+ const parsed = parseWithFormat(text, format, locale);
1028
+ if (
1029
+ parsed === null ||
1030
+ (Object.keys(parsed.fields).length === 0 && parsed.zone === undefined)
1031
+ ) {
1032
+ throw new RangeError(
1033
+ `Invalid date '${text}': it does not match the format '${format}'.`,
1034
+ );
1035
+ }
1036
+ if (parsed.zone !== undefined) assertZone(parsed.zone);
1037
+ const wallZone = parsed.zone ?? zone;
1038
+ const clock = resolveParsedFields(
1039
+ parsed.fields,
1040
+ nowWallClock(wallZone, parsed.offset),
1041
+ text,
1042
+ );
1043
+ const ms = instantOfParsed(clock, parsed, wallZone);
1044
+ const out = new DateTime(
1045
+ isoOfMs(ms, () => `'${text}'`),
1046
+ zone,
1047
+ );
1048
+ out.#locale = locale;
1049
+ return out;
1050
+ }
1051
+
403
1052
  // ─── Timezone ───────────────────────────────────────────
404
1053
 
405
1054
  get zoneName(): string {
@@ -410,12 +1059,74 @@ export class DateTime {
410
1059
  return nativeChronos().zoneOffset(this.#iso, this.#zone);
411
1060
  }
412
1061
 
413
- setZone(zone: string): DateTime {
414
- nativeChronos().validateTimezone(zone);
415
- return new DateTime(this.#iso, zone);
1062
+ /**
1063
+ * The same instant in another zone, or — with `keepLocalTime` — the same
1064
+ * wall clock in another zone (a different instant), as Luxon's `setZone`.
1065
+ */
1066
+ setZone(zone: string, options: { keepLocalTime?: boolean } = {}): DateTime {
1067
+ assertZone(zone);
1068
+ if (!options.keepLocalTime) return this.#derive(this.#iso, zone);
1069
+ return this.#derive(new Date(wallClockMs(this.calendar, zone)), zone);
416
1070
  }
417
1071
  toUTC(): DateTime {
418
- return new DateTime(this.#iso, "UTC");
1072
+ return this.#derive(this.#iso, "UTC");
1073
+ }
1074
+
1075
+ get locale(): string {
1076
+ return this.#locale;
1077
+ }
1078
+
1079
+ /** A copy whose names (`toFormat`) and `toLocaleString` default use `locale`. */
1080
+ setLocale(locale: string): DateTime {
1081
+ const [canonical] = Intl.getCanonicalLocales(locale);
1082
+ if (canonical === undefined)
1083
+ throw new RangeError(`Invalid locale: ${locale}`);
1084
+ const out = this.#derive(this.#iso);
1085
+ out.#locale = canonical;
1086
+ return out;
1087
+ }
1088
+
1089
+ /** Always true: chronos refuses invalid input instead of building an invalid value. */
1090
+ get isValid(): boolean {
1091
+ return true;
1092
+ }
1093
+
1094
+ /**
1095
+ * A copy with some calendar fields replaced, read on this value's wall
1096
+ * clock (Luxon's `set`). Changing the month keeps the day within it unless
1097
+ * the day is given too.
1098
+ *
1099
+ * @throws RangeError on a field out of range.
1100
+ */
1101
+ set(values: {
1102
+ year?: number;
1103
+ month?: number;
1104
+ day?: number;
1105
+ hour?: number;
1106
+ minute?: number;
1107
+ second?: number;
1108
+ millisecond?: number;
1109
+ }): DateTime {
1110
+ const c = this.calendar;
1111
+ const mixed: WallClock = {
1112
+ year: values.year ?? c.year,
1113
+ month: values.month ?? c.month,
1114
+ day: values.day ?? c.day,
1115
+ hour: values.hour ?? c.hour,
1116
+ minute: values.minute ?? c.minute,
1117
+ second: values.second ?? c.second,
1118
+ millisecond: values.millisecond ?? c.millisecond,
1119
+ };
1120
+ if (
1121
+ values.day === undefined &&
1122
+ Number.isInteger(mixed.month) &&
1123
+ mixed.month >= 1 &&
1124
+ mixed.month <= 12
1125
+ ) {
1126
+ mixed.day = Math.min(mixed.day, daysInMonthOf(mixed.year, mixed.month));
1127
+ }
1128
+ assertWallClock(mixed, JSON.stringify(values));
1129
+ return this.#derive(new Date(wallClockMs(mixed, this.#zone)));
419
1130
  }
420
1131
 
421
1132
  toZonedISO(): string {
@@ -425,29 +1136,181 @@ export class DateTime {
425
1136
 
426
1137
  // ─── Arithmetic ─────────────────────────────────────────
427
1138
 
428
- plus(amount: number, unit: DateUnit): DateTime {
1139
+ /**
1140
+ * Move by `amount` units. The whole part moves on the calendar (in the
1141
+ * value's zone for day/week/month/year); a fraction is carried as elapsed
1142
+ * time at Luxon's casual lengths (day 24 h, month 30 days, year 365 days),
1143
+ * so `plus(1.5, "day")` is one calendar day and twelve hours.
1144
+ *
1145
+ * @throws RangeError on a non-finite amount (NaN, ±Infinity, a non-number),
1146
+ * which the native boundary would otherwise read as 0, and on a result
1147
+ * outside years 0000-9999.
1148
+ */
1149
+ plus(amount: number, unit: DateUnit): DateTime;
1150
+ /**
1151
+ * Move by a duration, as Luxon's `plus(duration)`: whole years and months
1152
+ * first (one step, so Feb 29 + 1 year 1 month is Mar 29), then whole weeks
1153
+ * and days, both on the zone's calendar, then fractions and clock units as
1154
+ * elapsed time.
1155
+ */
1156
+ plus(duration: Duration | DurationObject): DateTime;
1157
+ plus(
1158
+ amountOrDuration: number | Duration | DurationObject,
1159
+ unit?: DateUnit,
1160
+ ): DateTime {
1161
+ if (typeof amountOrDuration === "object" && amountOrDuration !== null) {
1162
+ return this.#plusDuration(
1163
+ amountOrDuration instanceof Duration
1164
+ ? amountOrDuration
1165
+ : Duration.fromObject(amountOrDuration),
1166
+ );
1167
+ }
1168
+ if (unit === undefined) {
1169
+ throw new TypeError("plus(amount, unit) needs a unit");
1170
+ }
1171
+ return this.#plusUnit(amountOrDuration, unit);
1172
+ }
1173
+
1174
+ #plusDuration(duration: Duration): DateTime {
1175
+ const v = duration.toObject();
1176
+ const months = Math.trunc(v.years) * 12 + Math.trunc(v.months);
1177
+ const days = Math.trunc(v.weeks) * 7 + Math.trunc(v.days);
1178
+ const elapsed = Duration.fromObject({
1179
+ years: v.years - Math.trunc(v.years),
1180
+ months: v.months - Math.trunc(v.months),
1181
+ weeks: v.weeks - Math.trunc(v.weeks),
1182
+ days: v.days - Math.trunc(v.days),
1183
+ hours: v.hours,
1184
+ minutes: v.minutes,
1185
+ seconds: v.seconds,
1186
+ milliseconds: v.milliseconds,
1187
+ }).as("milliseconds");
1188
+ let out: DateTime = this.#plusUnit(months, "month");
1189
+ if (days !== 0) out = out.#plusUnit(days, "day");
1190
+ if (elapsed === 0) return out;
1191
+ return this.#derive(new Date(out.toMillis() + Math.round(elapsed)));
1192
+ }
1193
+
1194
+ #plusUnit(amount: number, unit: DateUnit): DateTime {
1195
+ if (typeof amount !== "number" || !Number.isFinite(amount)) {
1196
+ throw new RangeError(
1197
+ `Invalid unit value ${String(amount)}: plus/minus take a finite number`,
1198
+ );
1199
+ }
1200
+ const unitMs = casualUnitMs(unit);
1201
+ const whole = Math.trunc(amount);
1202
+ if (!Number.isSafeInteger(whole)) {
1203
+ throw new RangeError(
1204
+ `plus(${amount}, '${unit}') is out of range: years are limited to 0000-9999`,
1205
+ );
1206
+ }
429
1207
  const n = nativeChronos();
430
- const out =
431
- this.#zone !== "UTC" && isCalendarUnit(unit)
432
- ? n.addInZone(this.#iso, amount, unit, this.#zone)
433
- : n.add(this.#iso, amount, unit);
434
- return new DateTime(out, this.#zone);
1208
+ const shifted =
1209
+ whole === 0
1210
+ ? this.#iso
1211
+ : this.#zone !== "UTC" && isCalendarUnit(unit)
1212
+ ? n.addInZone(this.#iso, whole, unit, this.#zone)
1213
+ : n.add(this.#iso, whole, unit);
1214
+ const fraction = amount - whole;
1215
+ if (fraction === 0) return this.#derive(shifted);
1216
+ return this.#derive(
1217
+ new Date(Date.parse(shifted) + Math.round(fraction * unitMs)),
1218
+ );
1219
+ }
1220
+ minus(amount: number, unit: DateUnit): DateTime;
1221
+ /** Move back by a duration — `plus` of its negation, as in Luxon. */
1222
+ minus(duration: Duration | DurationObject): DateTime;
1223
+ minus(
1224
+ amountOrDuration: number | Duration | DurationObject,
1225
+ unit?: DateUnit,
1226
+ ): DateTime {
1227
+ if (typeof amountOrDuration === "object" && amountOrDuration !== null) {
1228
+ const duration =
1229
+ amountOrDuration instanceof Duration
1230
+ ? amountOrDuration
1231
+ : Duration.fromObject(amountOrDuration);
1232
+ return this.#plusDuration(duration.negate());
1233
+ }
1234
+ if (unit === undefined) {
1235
+ throw new TypeError("minus(amount, unit) needs a unit");
1236
+ }
1237
+ // Checked before negating: `-"1"` would turn a string into a number.
1238
+ if (typeof amountOrDuration !== "number") {
1239
+ throw new RangeError(
1240
+ `Invalid unit value ${String(amountOrDuration)}: plus/minus take a finite number`,
1241
+ );
1242
+ }
1243
+ return this.#plusUnit(-amountOrDuration, unit);
435
1244
  }
436
- minus(amount: number, unit: DateUnit): DateTime {
437
- return this.plus(-amount, unit);
1245
+
1246
+ /**
1247
+ * `this - other` as a Duration in the given unit(s), as Luxon's `diff`:
1248
+ * calendar units are counted on this value's calendar (a day across a DST
1249
+ * change is one day), the lowest unit keeps its fraction, and clock units
1250
+ * take what is left. `.as(unit)` reads it as a number.
1251
+ */
1252
+ diff(
1253
+ other: DateInput,
1254
+ unit:
1255
+ | DateUnit
1256
+ | DurationUnit
1257
+ | "millisecond"
1258
+ | ReadonlyArray<DateUnit | DurationUnit | "millisecond"> = "milliseconds",
1259
+ ): Duration {
1260
+ const units = (Array.isArray(unit) ? unit : [unit]).map(durationUnitOf);
1261
+ const ordered = DIFF_ORDER.filter((u) => units.includes(u));
1262
+ if (ordered.length === 0) throw new RangeError("diff needs a unit");
1263
+ const o = DateTime.from(other).setZone(this.#zone);
1264
+ const thisIsLater = this.toMillis() >= o.toMillis();
1265
+ const earlier = thisIsLater ? o : this;
1266
+ const later = thisIsLater ? this : o;
1267
+
1268
+ const calendar = ordered.filter((u) => CALENDAR_UNITS.has(u));
1269
+ const clock = ordered.filter((u) => !CALENDAR_UNITS.has(u));
1270
+ const results: DurationObject = {};
1271
+ let cursor = earlier;
1272
+ for (const u of calendar) {
1273
+ results[u] = Math.trunc(later.#diffNumber(cursor, u));
1274
+ cursor = earlier.plus(results);
1275
+ }
1276
+ let out: Duration;
1277
+ const lowest = calendar.at(-1);
1278
+ if (clock.length === 0 && lowest !== undefined) {
1279
+ results[lowest] =
1280
+ (results[lowest] ?? 0) + later.#diffNumber(cursor, lowest);
1281
+ out = Duration.fromObject(results);
1282
+ } else {
1283
+ out = Duration.fromMillis(later.toMillis() - cursor.toMillis())
1284
+ .shiftTo(...clock)
1285
+ .plus(results);
1286
+ }
1287
+ return thisIsLater ? out : out.negate();
438
1288
  }
439
1289
 
440
- diff(other: DateInput, unit: DateUnit): number {
1290
+ /** `this - other` in one unit, as a fractional number (calendar-aware). */
1291
+ #diffNumber(other: DateTime, unit: DurationUnit): number {
441
1292
  const n = nativeChronos();
442
- const otherIso = toIso(other);
443
- return this.#zone !== "UTC" && (unit === "month" || unit === "year")
444
- ? n.diffInZone(this.#iso, otherIso, unit, this.#zone)
445
- : n.diff(this.#iso, otherIso, unit);
1293
+ const singular = unit.slice(0, -1);
1294
+ return CALENDAR_UNITS.has(unit)
1295
+ ? n.diffInZone(this.#iso, other.#iso, singular, this.#zone)
1296
+ : n.diff(this.#iso, other.#iso, unit);
446
1297
  }
447
1298
 
448
1299
  // ─── Comparison ─────────────────────────────────────────
449
1300
 
1301
+ /**
1302
+ * Same instant — and, against another DateTime, same zone and locale, as
1303
+ * Luxon's `equals`. Compare `toMillis()` (or use `<`, `>`) for the instant
1304
+ * alone.
1305
+ */
450
1306
  equals(other: DateInput): boolean {
1307
+ if (other instanceof DateTime) {
1308
+ return (
1309
+ this.#iso === other.#iso &&
1310
+ this.#zone === other.#zone &&
1311
+ this.#locale === other.#locale
1312
+ );
1313
+ }
451
1314
  return this.#iso === toIso(other);
452
1315
  }
453
1316
  isBefore(other: DateInput): boolean {
@@ -456,10 +1319,10 @@ export class DateTime {
456
1319
  isAfter(other: DateInput): boolean {
457
1320
  return toMs(this) > toMs(other);
458
1321
  }
1322
+ /** Whether `other` falls in the same `unit` as this value, on this value's calendar. */
459
1323
  hasSame(other: DateInput, unit: BoundUnit): boolean {
460
- return (
461
- this.startOf(unit).toISO() === DateTime.from(other).startOf(unit).toISO()
462
- );
1324
+ const o = DateTime.from(other).setZone(this.#zone);
1325
+ return this.startOf(unit).toMillis() === o.startOf(unit).toMillis();
463
1326
  }
464
1327
  isSameDay(other: DateInput): boolean {
465
1328
  return this.hasSame(other, "day");
@@ -477,22 +1340,20 @@ export class DateTime {
477
1340
  */
478
1341
  startOf(unit: BoundUnit): DateTime {
479
1342
  const n = nativeChronos();
480
- return new DateTime(
1343
+ return this.#derive(
481
1344
  this.#zone === "UTC"
482
1345
  ? n.startOf(this.#iso, unit)
483
1346
  : n.startOfInZone(this.#iso, unit, this.#zone),
484
- this.#zone,
485
1347
  );
486
1348
  }
487
1349
 
488
1350
  /** The last instant of `unit` — see {@link startOf} on the shared routine. */
489
1351
  endOf(unit: BoundUnit): DateTime {
490
1352
  const n = nativeChronos();
491
- return new DateTime(
1353
+ return this.#derive(
492
1354
  this.#zone === "UTC"
493
1355
  ? n.endOf(this.#iso, unit)
494
1356
  : n.endOfInZone(this.#iso, unit, this.#zone),
495
- this.#zone,
496
1357
  );
497
1358
  }
498
1359
 
@@ -504,6 +1365,11 @@ export class DateTime {
504
1365
 
505
1366
  // ─── Formatting ─────────────────────────────────────────
506
1367
 
1368
+ /**
1369
+ * Format with chronos's moment-style tokens (`YYYY`, `YY`, `MM`, `DD`,
1370
+ * `HH`, `mm`, `ss`, `Z`; `[text]` is literal) on this value's wall clock.
1371
+ * Luxon's tokens (`yyyy`, `dd`, `LLL`, …) are {@link toFormat}.
1372
+ */
507
1373
  format(pattern = "YYYY-MM-DD HH:mm:ss"): string {
508
1374
  if (this.#zone !== "UTC") {
509
1375
  return formatFromIsoString(
@@ -514,21 +1380,98 @@ export class DateTime {
514
1380
  return nativeChronos().format(this.#iso, pattern);
515
1381
  }
516
1382
 
1383
+ /**
1384
+ * Format with Luxon's tokens (`yyyy-MM-dd HH:mm`, `dd LLL yyyy`, `EEEE`,
1385
+ * `ZZ`, macros such as `DD` or `t`; `'quoted'` text is literal), on this
1386
+ * value's wall clock. {@link format} keeps chronos's moment-style tokens.
1387
+ */
1388
+ toFormat(pattern: string): string {
1389
+ return this.#luxonFormat(pattern, false);
1390
+ }
1391
+
1392
+ /** `allowZ`: a UTC value writes its offset as `Z` (ISO and SQL output). */
1393
+ #luxonFormat(pattern: string, allowZ = true): string {
1394
+ return formatLuxon(pattern, {
1395
+ parts: this.calendar,
1396
+ ts: this.toMillis(),
1397
+ offset: this.offset,
1398
+ zone: this.#zone,
1399
+ locale: this.#locale,
1400
+ allowZ: allowZ && this.#zone === "UTC",
1401
+ });
1402
+ }
1403
+
517
1404
  toDate(): Date {
518
1405
  return new Date(this.#iso);
519
1406
  }
520
- toISO(): string {
521
- return this.#iso;
1407
+
1408
+ /**
1409
+ * ISO 8601 on this value's wall clock, as Luxon's `toISO`: `…Z` in UTC,
1410
+ * the local offset (`2026-08-10T12:00:00.000+02:00`) in any other zone —
1411
+ * the same instant either way.
1412
+ */
1413
+ toISO(
1414
+ options: { suppressMilliseconds?: boolean; includeOffset?: boolean } = {},
1415
+ ): string {
1416
+ const plain =
1417
+ options.suppressMilliseconds !== true && options.includeOffset !== false;
1418
+ if (this.#zone === "UTC" && plain) return this.#iso;
1419
+ return this.#luxonFormat(`yyyy-MM-dd'T'${this.#timeFormat(options)}`);
1420
+ }
1421
+
1422
+ #timeFormat(options: {
1423
+ suppressMilliseconds?: boolean;
1424
+ includeOffset?: boolean;
1425
+ }): string {
1426
+ const ms =
1427
+ options.suppressMilliseconds === true && this.millisecond === 0
1428
+ ? ""
1429
+ : ".SSS";
1430
+ return `HH:mm:ss${ms}${options.includeOffset === false ? "" : "ZZ"}`;
1431
+ }
1432
+
1433
+ /** `yyyy-MM-dd` on this value's calendar. */
1434
+ toISODate(): string {
1435
+ return this.#luxonFormat("yyyy-MM-dd");
1436
+ }
1437
+
1438
+ /** `HH:mm:ss.SSS` plus the offset, on this value's wall clock. */
1439
+ toISOTime(
1440
+ options: { suppressMilliseconds?: boolean; includeOffset?: boolean } = {},
1441
+ ): string {
1442
+ return this.#luxonFormat(this.#timeFormat(options));
1443
+ }
1444
+
1445
+ /** `yyyy-MM-dd`, as SQL writes a date. */
1446
+ toSQLDate(): string {
1447
+ return this.toISODate();
1448
+ }
1449
+
1450
+ /** `HH:mm:ss.SSS +02:00` (`Z` in UTC), as Luxon's `toSQLTime`. */
1451
+ toSQLTime(options: { includeOffset?: boolean } = {}): string {
1452
+ return this.#luxonFormat(
1453
+ options.includeOffset === false ? "HH:mm:ss.SSS" : "HH:mm:ss.SSS ZZ",
1454
+ );
1455
+ }
1456
+
1457
+ /** `yyyy-MM-dd HH:mm:ss.SSS +02:00`, as Luxon's `toSQL`. */
1458
+ toSQL(options: { includeOffset?: boolean } = {}): string {
1459
+ return `${this.toSQLDate()} ${this.toSQLTime(options)}`;
522
1460
  }
1461
+
523
1462
  toString(): string {
524
- return this.#iso;
1463
+ return this.toISO();
525
1464
  }
526
1465
  toJSON(): string {
527
- return this.#iso;
1466
+ return this.toISO();
528
1467
  }
529
1468
  toMillis(): number {
530
1469
  return new Date(this.#iso).getTime();
531
1470
  }
1471
+ /** Epoch milliseconds, so `a < b` and `a - b` work as with Luxon. */
1472
+ valueOf(): number {
1473
+ return this.toMillis();
1474
+ }
532
1475
  toSeconds(): number {
533
1476
  return Math.floor(this.toMillis() / 1000);
534
1477
  }
@@ -537,43 +1480,65 @@ export class DateTime {
537
1480
  locale?: Intl.LocalesArgument,
538
1481
  options?: Intl.DateTimeFormatOptions,
539
1482
  ): string {
540
- return new Intl.DateTimeFormat(locale, {
541
- ...(this.#zone !== "UTC" ? { timeZone: this.#zone } : {}),
1483
+ // The value's own zone, UTC included: without it Intl falls back to the
1484
+ // host's zone and the same value prints differently per machine.
1485
+ return new Intl.DateTimeFormat(locale ?? this.#locale, {
1486
+ timeZone: this.#zone,
542
1487
  ...options,
543
1488
  }).format(this.toDate());
544
1489
  }
545
1490
 
546
- toRelative(options?: {
547
- base?: DateInput;
548
- locale?: Intl.LocalesArgument;
549
- }): string {
550
- const base = options?.base ? DateTime.from(options.base) : new DateTime();
551
- const diffMs = this.toMillis() - base.toMillis();
552
- const abs = Math.abs(diffMs);
553
- let unit: Intl.RelativeTimeFormatUnit;
554
- let value: number;
555
- if (abs < 60_000) {
556
- unit = "second";
557
- value = Math.round(diffMs / 1000);
558
- } else if (abs < 3_600_000) {
559
- unit = "minute";
560
- value = Math.round(diffMs / 60_000);
561
- } else if (abs < 86_400_000) {
562
- unit = "hour";
563
- value = Math.round(diffMs / 3_600_000);
564
- } else if (abs < 2_592_000_000) {
565
- unit = "day";
566
- value = Math.round(diffMs / 86_400_000);
567
- } else if (abs < 31_536_000_000) {
568
- unit = "month";
569
- value = Math.round(diffMs / 2_592_000_000);
570
- } else {
571
- unit = "year";
572
- value = Math.round(diffMs / 31_536_000_000);
1491
+ /**
1492
+ * This value relative to `base` (now by default), as Luxon's `toRelative`:
1493
+ * "in 1 day", "48 hours ago". The count is the calendar-aware diff in the
1494
+ * largest unit that reaches 1, truncated toward zero, always as a number
1495
+ * ("1 day ago", never "yesterday": that is {@link toRelativeCalendar}).
1496
+ * Formatted in this value's locale unless `locale` is given.
1497
+ *
1498
+ * NAMED DEVIATION: no `quarters` unit, as chronos's Duration has none.
1499
+ */
1500
+ toRelative(options: ToRelativeOptions = {}): string {
1501
+ const base =
1502
+ options.base === undefined
1503
+ ? DateTime.now(this.#zone)
1504
+ : DateTime.from(options.base);
1505
+ const padding = options.padding
1506
+ ? this.toMillis() < base.toMillis()
1507
+ ? -options.padding
1508
+ : options.padding
1509
+ : 0;
1510
+ let units = TO_RELATIVE_UNITS;
1511
+ let unit: RelativeUnit | undefined;
1512
+ if (Array.isArray(options.unit)) {
1513
+ units = options.unit.map(relativeUnitOf);
1514
+ } else if (options.unit !== undefined) {
1515
+ unit = relativeUnitOf(options.unit);
573
1516
  }
574
- return new Intl.RelativeTimeFormat(options?.locale as string | undefined, {
1517
+ return diffRelative(
1518
+ base,
1519
+ padding === 0 ? this : this.plus({ milliseconds: padding }),
1520
+ { ...options, numeric: "always", units, unit, calendary: false },
1521
+ );
1522
+ }
1523
+
1524
+ /**
1525
+ * This value relative to `base`'s calendar, as Luxon's
1526
+ * `toRelativeCalendar`: "yesterday", "next month", "3 days ago". Counts the
1527
+ * calendar boundaries crossed in years, months, then days, or in `unit`.
1528
+ */
1529
+ toRelativeCalendar(options: ToRelativeCalendarOptions = {}): string {
1530
+ const base =
1531
+ options.base === undefined
1532
+ ? DateTime.now(this.#zone)
1533
+ : DateTime.from(options.base);
1534
+ return diffRelative(base, this, {
1535
+ ...options,
575
1536
  numeric: "auto",
576
- }).format(value, unit);
1537
+ units: TO_RELATIVE_CALENDAR_UNITS,
1538
+ unit:
1539
+ options.unit === undefined ? undefined : relativeUnitOf(options.unit),
1540
+ calendary: true,
1541
+ });
577
1542
  }
578
1543
 
579
1544
  // ─── Calendar accessors ─────────────────────────────────
@@ -584,7 +1549,7 @@ export class DateTime {
584
1549
  nativeChronos().toZone(this.#iso, this.#zone).iso,
585
1550
  );
586
1551
  }
587
- return nativeChronos().calendarParts(this.#iso) as CalendarParts;
1552
+ return nativeChronos().calendarParts(this.#iso);
588
1553
  }
589
1554
  get weekday(): number {
590
1555
  return this.calendar.weekday;