@c9up/chronos 0.1.15 → 0.1.16

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 (52) hide show
  1. package/README.md +63 -16
  2. package/dist/DateTime.d.ts +145 -4
  3. package/dist/DateTime.d.ts.map +1 -1
  4. package/dist/DateTime.js +504 -87
  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 +37 -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/index.d.ts +5 -5
  23. package/dist/index.d.ts.map +1 -1
  24. package/dist/index.js +3 -3
  25. package/dist/index.js.map +1 -1
  26. package/dist/native/generated.d.ts +2 -2
  27. package/dist/native/generated.d.ts.map +1 -1
  28. package/dist/native.js +2 -2
  29. package/dist/native.js.map +1 -1
  30. package/dist/rrule.d.ts +25 -1
  31. package/dist/rrule.d.ts.map +1 -1
  32. package/dist/rrule.js +130 -32
  33. package/dist/rrule.js.map +1 -1
  34. package/index.darwin-arm64.node +0 -0
  35. package/index.darwin-x64.node +0 -0
  36. package/index.linux-arm64-gnu.node +0 -0
  37. package/index.linux-x64-gnu.node +0 -0
  38. package/index.win32-x64-msvc.node +0 -0
  39. package/package.json +1 -1
  40. package/src/DateTime.ts +645 -96
  41. package/src/Duration.ts +318 -139
  42. package/src/Interval.ts +160 -53
  43. package/src/atlas.ts +23 -17
  44. package/src/format.ts +449 -0
  45. package/src/index.ts +17 -7
  46. package/src/native/generated.ts +6 -2
  47. package/src/native.ts +3 -3
  48. package/src/rrule.ts +189 -37
  49. package/wasm/chronos_engine_wasm.d.ts +4 -4
  50. package/wasm/chronos_engine_wasm.js +26 -16
  51. package/wasm/chronos_engine_wasm_bg.wasm +0 -0
  52. package/wasm/chronos_engine_wasm_bg.wasm.d.ts +2 -2
package/src/DateTime.ts CHANGED
@@ -10,6 +10,12 @@
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
20
  import { normalizeIso } from "./utils.js";
15
21
 
@@ -110,53 +116,192 @@ function daysInMonthOf(year: number, month: number): number {
110
116
  }
111
117
 
112
118
  /**
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.
119
+ * The only strings a `DateTime` reads: ISO 8601 calendar dates, optionally with
120
+ * a time (`T` or, as SQL writes it, a space) and an offset (`Z`, `±HH`,
121
+ * `±HHMM`, `±HH:MM`). Anything else is refused: V8's fallback parser turns
122
+ * `"1"` or `"foo 2026"` into a date, and reads an offset-less time in the
123
+ * HOST zone, so the same text named a different instant on every machine.
124
+ */
125
+ const ISO_8601 =
126
+ /^(\d{4})-(\d{2})-(\d{2})(?:[Tt ](\d{2}):(\d{2})(?::(\d{2})(?:[.,](\d{1,9}))?)?(?:\s?([Zz])|\s?([+-])(\d{2})(?::?(\d{2}))?)?)?$/;
127
+
128
+ /** First and last instants a value may hold: what a four-digit ISO year writes. */
129
+ const MIN_MS = -62_167_219_200_000; // 0000-01-01T00:00:00.000Z
130
+ const MAX_MS = 253_402_300_799_999; // 9999-12-31T23:59:59.999Z
131
+
132
+ interface WallClock {
133
+ year: number;
134
+ month: number;
135
+ day: number;
136
+ hour: number;
137
+ minute: number;
138
+ second: number;
139
+ millisecond: number;
140
+ }
141
+
142
+ /**
143
+ * Refuse a wall-clock value that does not exist, instead of sliding to the
144
+ * next one that does.
122
145
  *
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.
146
+ * `new Date('2026-02-30')` answers 2026-03-02 and `Date.UTC(…, 10, 90)` reads
147
+ * minute 90 as 11:30: the overflow semantics are right for arithmetic — adding
148
+ * a month to January 31st has to land somewhere — and wrong for reading input,
149
+ * where the same slide turns a typo into a fact. Only the written value is
150
+ * examined, never the instant it resolves to, so an offset that legitimately
151
+ * moves the UTC day ('2026-08-10T23:00:00-05:00' → the 11th) is untouched.
127
152
  */
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) {
143
- throw new Error(
144
- `Invalid date '${raw}': ${MONTH_NAMES[month - 1]} ${year} has ${lastDay} days, so there is no day ${day}.`,
153
+ function assertWallClock(c: WallClock, raw: string): void {
154
+ const integer = (unit: string, value: number, min: number, max: number) => {
155
+ if (!Number.isInteger(value) || value < min || value > max) {
156
+ throw new RangeError(
157
+ `Invalid date '${raw}': ${unit} ${String(value)} is out of range (${min}-${max}).`,
158
+ );
159
+ }
160
+ };
161
+ integer("year", c.year, 0, 9999);
162
+ if (!Number.isInteger(c.month) || c.month < 1 || c.month > 12) {
163
+ throw new RangeError(
164
+ `Invalid date '${raw}': there is no month ${String(c.month)}.`,
165
+ );
166
+ }
167
+ const lastDay = daysInMonthOf(c.year, c.month);
168
+ if (!Number.isInteger(c.day) || c.day < 1 || c.day > lastDay) {
169
+ throw new RangeError(
170
+ `Invalid date '${raw}': ${MONTH_NAMES[c.month - 1]} ${c.year} has ${lastDay} days, so there is no day ${String(c.day)}.`,
145
171
  );
146
172
  }
173
+ integer("hour", c.hour, 0, 23);
174
+ integer("minute", c.minute, 0, 59);
175
+ integer("second", c.second, 0, 59);
176
+ integer("millisecond", c.millisecond, 0, 999);
177
+ }
178
+
179
+ /** Epoch milliseconds of a UTC wall clock; years 0-99 stay literal (Date.UTC maps them to 19xx). */
180
+ function utcMs(c: WallClock): number {
181
+ const d = new Date(0);
182
+ d.setUTCFullYear(c.year, c.month - 1, c.day);
183
+ d.setUTCHours(c.hour, c.minute, c.second, c.millisecond);
184
+ return d.getTime();
147
185
  }
148
186
 
149
- function toIso(value: DateInput): string {
187
+ const pad = (n: number, width = 2): string => String(n).padStart(width, "0");
188
+
189
+ /** Epoch milliseconds of a wall clock read in `zone`. */
190
+ function wallClockMs(c: WallClock, zone: string): number {
191
+ if (zone === "UTC") return utcMs(c);
192
+ const naive = `${pad(c.year, 4)}-${pad(c.month)}-${pad(c.day)}T${pad(c.hour)}:${pad(c.minute)}:${pad(c.second)}`;
193
+ return Date.parse(nativeChronos().fromLocal(naive, zone)) + c.millisecond;
194
+ }
195
+
196
+ /** The canonical UTC ISO string of an instant, refusing what chronos cannot hold. */
197
+ function isoOfMs(ms: number, input: () => string): string {
198
+ if (!Number.isFinite(ms)) throw new RangeError(`Invalid date ${input()}`);
199
+ if (ms < MIN_MS || ms > MAX_MS) {
200
+ throw new RangeError(
201
+ `Date ${input()} is out of range: years are limited to 0000-9999.`,
202
+ );
203
+ }
204
+ return new Date(ms).toISOString();
205
+ }
206
+
207
+ /** Read an ISO 8601 string; an offset-less one is a wall clock in `zone`. */
208
+ function parseIso(raw: string, zone: string): string {
209
+ const m = ISO_8601.exec(raw);
210
+ if (!m) {
211
+ throw new RangeError(
212
+ `Invalid date '${raw}': expected ISO 8601 (YYYY-MM-DD, optionally with THH:mm[:ss[.SSS]] and an offset).`,
213
+ );
214
+ }
215
+ const c: WallClock = {
216
+ year: Number(m[1]),
217
+ month: Number(m[2]),
218
+ day: Number(m[3]),
219
+ hour: Number(m[4] ?? 0),
220
+ minute: Number(m[5] ?? 0),
221
+ second: Number(m[6] ?? 0),
222
+ millisecond: Math.floor(Number(`0.${m[7] ?? "0"}`) * 1000),
223
+ };
224
+ assertWallClock(c, raw);
225
+ let ms: number;
226
+ if (m[8] !== undefined) {
227
+ ms = utcMs(c);
228
+ } else if (m[9] !== undefined) {
229
+ const hours = Number(m[10]);
230
+ const minutes = Number(m[11] ?? 0);
231
+ if (hours > 23 || minutes > 59) {
232
+ throw new RangeError(
233
+ `Invalid date '${raw}': the offset is out of range.`,
234
+ );
235
+ }
236
+ const sign = m[9] === "-" ? -1 : 1;
237
+ ms = utcMs(c) - sign * (hours * 60 + minutes) * 60_000;
238
+ } else {
239
+ ms = wallClockMs(c, zone);
240
+ }
241
+ return isoOfMs(ms, () => `'${raw}'`);
242
+ }
243
+
244
+ function toIso(value: DateInput, zone = "UTC"): string {
150
245
  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());
246
+ if (value instanceof Date) {
247
+ return normalizeIso(isoOfMs(value.getTime(), () => "(JS Date)"));
248
+ }
249
+ if (typeof value !== "string") {
250
+ throw new TypeError(
251
+ `Invalid date input: expected a string, a Date or a DateTime, got ${typeof value}`,
252
+ );
253
+ }
254
+ return normalizeIso(parseIso(value, zone));
154
255
  }
155
256
 
156
257
  function toMs(value: DateInput): number {
157
258
  return new Date(toIso(value)).getTime();
158
259
  }
159
260
 
261
+ const CASUAL_UNIT_MS: Readonly<Record<string, number>> = {
262
+ second: 1_000,
263
+ minute: 60_000,
264
+ hour: 3_600_000,
265
+ day: 86_400_000,
266
+ week: 604_800_000,
267
+ month: 30 * 86_400_000,
268
+ year: 365 * 86_400_000,
269
+ };
270
+
271
+ /** Milliseconds in one unit on Luxon's casual matrix; throws on an unknown unit. */
272
+ function casualUnitMs(unit: string): number {
273
+ const singular = unit.endsWith("s") ? unit.slice(0, -1) : unit;
274
+ const ms = Object.hasOwn(CASUAL_UNIT_MS, singular)
275
+ ? CASUAL_UNIT_MS[singular]
276
+ : undefined;
277
+ if (ms === undefined) throw new Error(`Unsupported unit: ${unit}`);
278
+ return ms;
279
+ }
280
+
281
+ const DIFF_ORDER: readonly DurationUnit[] = [
282
+ "years",
283
+ "months",
284
+ "weeks",
285
+ "days",
286
+ "hours",
287
+ "minutes",
288
+ "seconds",
289
+ "milliseconds",
290
+ ];
291
+ const CALENDAR_UNITS: ReadonlySet<DurationUnit> = new Set([
292
+ "years",
293
+ "months",
294
+ "weeks",
295
+ "days",
296
+ ]);
297
+
298
+ function durationUnitOf(unit: string): DurationUnit {
299
+ const plural = unit.endsWith("s") ? unit : `${unit}s`;
300
+ const found = DIFF_ORDER.find((u) => u === plural);
301
+ if (found === undefined) throw new RangeError(`Unsupported unit: ${unit}`);
302
+ return found;
303
+ }
304
+
160
305
  function isCalendarUnit(unit: DateUnit): boolean {
161
306
  return (
162
307
  unit === "day" || unit === "week" || unit === "month" || unit === "year"
@@ -331,25 +476,106 @@ function rangesOverlap(
331
476
  : Math.max(na.start, nb.start) < Math.min(na.end, nb.end);
332
477
  }
333
478
 
479
+ // ─── Zone validation ─────────────────────────────────────────
480
+
481
+ /**
482
+ * Zones the engine has already accepted, exactly as it names them.
483
+ *
484
+ * Every derived value (`plus`, `startOf`, …) is built through the constructor
485
+ * with the zone of the value it came from, so without this each one would pay
486
+ * a native call to re-validate a zone that was checked on the way in. Only a
487
+ * name equal to the engine's canonical spelling is remembered: the set is then
488
+ * bounded by the tz database, whatever spellings a caller sends.
489
+ */
490
+ const acceptedZones = new Set<string>(["UTC"]);
491
+
492
+ /**
493
+ * Throw on a zone the tz database does not know — the one check behind every
494
+ * entry that takes a zone (`new DateTime(input, zone)`, `DateTime.now(zone)`,
495
+ * `setZone`), so all three refuse the same names with the same message.
496
+ */
497
+ function assertZone(zone: string): void {
498
+ if (acceptedZones.has(zone)) return;
499
+ const canonical = nativeChronos().validateTimezone(zone);
500
+ if (canonical === zone) acceptedZones.add(zone);
501
+ }
502
+
334
503
  // ─── DateTime class ──────────────────────────────────────────
335
504
 
336
505
  export class DateTime {
337
506
  #iso: string;
338
507
  #zone: string;
508
+ /** Locale for names in `toFormat` and for `toLocaleString`; en-US unless set. */
509
+ #locale = "en-US";
339
510
 
511
+ /**
512
+ * @throws on a zone the tz database does not know. An unknown zone used to
513
+ * be stored as given and break later, on the first offset or format.
514
+ */
340
515
  constructor(input: string | Date = new Date(), zone = "UTC") {
341
- this.#iso = toIso(input);
516
+ assertZone(zone);
517
+ this.#iso = toIso(input, zone);
342
518
  this.#zone = zone;
343
519
  }
344
520
 
345
521
  static from(input: DateInput): DateTime {
346
- if (input instanceof DateTime) return new DateTime(input.#iso, input.#zone);
522
+ if (input instanceof DateTime) return input.#derive(input.#iso);
347
523
  return new DateTime(toIso(input));
348
524
  }
525
+
526
+ /** A value derived from this one: same zone (unless given) and locale. */
527
+ #derive(input: string | Date, zone = this.#zone): DateTime {
528
+ const out = new DateTime(input, zone);
529
+ out.#locale = this.#locale;
530
+ return out;
531
+ }
532
+
533
+ /** Now, or the given wall clock, in the host's zone (Luxon's `DateTime.local`). */
534
+ static local(
535
+ year?: number,
536
+ month = 1,
537
+ day = 1,
538
+ hour = 0,
539
+ minute = 0,
540
+ second = 0,
541
+ millisecond = 0,
542
+ ): DateTime {
543
+ const zone = Intl.DateTimeFormat().resolvedOptions().timeZone;
544
+ if (year === undefined) return DateTime.now(zone);
545
+ return DateTime.fromObject(
546
+ { year, month, day, hour, minute, second, millisecond },
547
+ { zone },
548
+ );
549
+ }
550
+
551
+ /** Now, or the given wall clock, in UTC (Luxon's `DateTime.utc`). */
552
+ static utc(
553
+ year?: number,
554
+ month = 1,
555
+ day = 1,
556
+ hour = 0,
557
+ minute = 0,
558
+ second = 0,
559
+ millisecond = 0,
560
+ ): DateTime {
561
+ if (year === undefined) return DateTime.now();
562
+ return DateTime.fromObject({
563
+ year,
564
+ month,
565
+ day,
566
+ hour,
567
+ minute,
568
+ second,
569
+ millisecond,
570
+ });
571
+ }
349
572
  static now(zone?: string): DateTime {
350
573
  return new DateTime(new Date(), zone ?? "UTC");
351
574
  }
352
575
  static fromMillis(ms: number): DateTime {
576
+ if (typeof ms !== "number") {
577
+ throw new TypeError(`fromMillis expects a number, got ${typeof ms}`);
578
+ }
353
579
  return new DateTime(new Date(ms));
354
580
  }
355
581
  static fromSeconds(seconds: number): DateTime {
@@ -362,39 +588,66 @@ export class DateTime {
362
588
  if (!Number.isFinite(date.getTime())) throw new Error("Invalid Date");
363
589
  return new DateTime(date);
364
590
  }
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
- ),
591
+ /**
592
+ * Read an ISO 8601 string. An offset-less one is a wall clock in
593
+ * `options.zone` (UTC by default), and the result is in that zone.
594
+ */
595
+ static fromISO(text: string, options: { zone?: string } = {}): DateTime {
596
+ return new DateTime(text, options.zone ?? "UTC");
597
+ }
598
+
599
+ /**
600
+ * Build from calendar fields, read as a wall clock in `options.zone` (UTC by
601
+ * default). Every field is checked: an integer within its range (minute
602
+ * 0-59, …), and a year read literally (50 is year 0050, not 1950).
603
+ */
604
+ static fromObject(
605
+ obj: {
606
+ year: number;
607
+ month: number;
608
+ day: number;
609
+ hour?: number;
610
+ minute?: number;
611
+ second?: number;
612
+ millisecond?: number;
613
+ /** @deprecated spelled `millisecond`, as Luxon does. */
614
+ ms?: number;
615
+ },
616
+ options: { zone?: string } = {},
617
+ ): DateTime {
618
+ const zone = options.zone ?? "UTC";
619
+ assertZone(zone);
620
+ const c: WallClock = {
621
+ year: obj.year,
622
+ month: obj.month,
623
+ day: obj.day,
624
+ hour: obj.hour ?? 0,
625
+ minute: obj.minute ?? 0,
626
+ second: obj.second ?? 0,
627
+ millisecond: obj.millisecond ?? obj.ms ?? 0,
628
+ };
629
+ assertWallClock(c, JSON.stringify(obj));
630
+ return new DateTime(
631
+ isoOfMs(wallClockMs(c, zone), () => JSON.stringify(obj)),
632
+ zone,
387
633
  );
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
634
  }
393
635
  static fromRFC2822(input: string): DateTime {
394
636
  return new DateTime(nativeChronos().parseRfc2822(input));
395
637
  }
396
- static fromSQL(input: string): DateTime {
397
- return new DateTime(nativeChronos().parseSql(input));
638
+ /**
639
+ * Read a SQL literal: `YYYY-MM-DD`, or `YYYY-MM-DD HH:mm[:ss[.fff]]` with an
640
+ * optional offset (`+00`, `+02:00` — PostgreSQL's `timestamptz` text) or
641
+ * IANA zone. Without one, the value is a wall clock in `options.zone` (UTC
642
+ * by default), and the result is in that zone.
643
+ */
644
+ static fromSQL(input: string, options: { zone?: string } = {}): DateTime {
645
+ const zone = options.zone ?? "UTC";
646
+ assertZone(zone);
647
+ return new DateTime(
648
+ nativeChronos().parseSql(input, zone === "UTC" ? undefined : zone),
649
+ zone,
650
+ );
398
651
  }
399
652
  static fromHTTP(input: string): DateTime {
400
653
  return new DateTime(nativeChronos().parseHttp(input));
@@ -410,12 +663,74 @@ export class DateTime {
410
663
  return nativeChronos().zoneOffset(this.#iso, this.#zone);
411
664
  }
412
665
 
413
- setZone(zone: string): DateTime {
414
- nativeChronos().validateTimezone(zone);
415
- return new DateTime(this.#iso, zone);
666
+ /**
667
+ * The same instant in another zone, or — with `keepLocalTime` — the same
668
+ * wall clock in another zone (a different instant), as Luxon's `setZone`.
669
+ */
670
+ setZone(zone: string, options: { keepLocalTime?: boolean } = {}): DateTime {
671
+ assertZone(zone);
672
+ if (!options.keepLocalTime) return this.#derive(this.#iso, zone);
673
+ return this.#derive(new Date(wallClockMs(this.calendar, zone)), zone);
416
674
  }
417
675
  toUTC(): DateTime {
418
- return new DateTime(this.#iso, "UTC");
676
+ return this.#derive(this.#iso, "UTC");
677
+ }
678
+
679
+ get locale(): string {
680
+ return this.#locale;
681
+ }
682
+
683
+ /** A copy whose names (`toFormat`) and `toLocaleString` default use `locale`. */
684
+ setLocale(locale: string): DateTime {
685
+ const [canonical] = Intl.getCanonicalLocales(locale);
686
+ if (canonical === undefined)
687
+ throw new RangeError(`Invalid locale: ${locale}`);
688
+ const out = this.#derive(this.#iso);
689
+ out.#locale = canonical;
690
+ return out;
691
+ }
692
+
693
+ /** Always true: chronos refuses invalid input instead of building an invalid value. */
694
+ get isValid(): boolean {
695
+ return true;
696
+ }
697
+
698
+ /**
699
+ * A copy with some calendar fields replaced, read on this value's wall
700
+ * clock (Luxon's `set`). Changing the month keeps the day within it unless
701
+ * the day is given too.
702
+ *
703
+ * @throws RangeError on a field out of range.
704
+ */
705
+ set(values: {
706
+ year?: number;
707
+ month?: number;
708
+ day?: number;
709
+ hour?: number;
710
+ minute?: number;
711
+ second?: number;
712
+ millisecond?: number;
713
+ }): DateTime {
714
+ const c = this.calendar;
715
+ const mixed: WallClock = {
716
+ year: values.year ?? c.year,
717
+ month: values.month ?? c.month,
718
+ day: values.day ?? c.day,
719
+ hour: values.hour ?? c.hour,
720
+ minute: values.minute ?? c.minute,
721
+ second: values.second ?? c.second,
722
+ millisecond: values.millisecond ?? c.millisecond,
723
+ };
724
+ if (
725
+ values.day === undefined &&
726
+ Number.isInteger(mixed.month) &&
727
+ mixed.month >= 1 &&
728
+ mixed.month <= 12
729
+ ) {
730
+ mixed.day = Math.min(mixed.day, daysInMonthOf(mixed.year, mixed.month));
731
+ }
732
+ assertWallClock(mixed, JSON.stringify(values));
733
+ return this.#derive(new Date(wallClockMs(mixed, this.#zone)));
419
734
  }
420
735
 
421
736
  toZonedISO(): string {
@@ -425,29 +740,181 @@ export class DateTime {
425
740
 
426
741
  // ─── Arithmetic ─────────────────────────────────────────
427
742
 
428
- plus(amount: number, unit: DateUnit): DateTime {
743
+ /**
744
+ * Move by `amount` units. The whole part moves on the calendar (in the
745
+ * value's zone for day/week/month/year); a fraction is carried as elapsed
746
+ * time at Luxon's casual lengths (day 24 h, month 30 days, year 365 days),
747
+ * so `plus(1.5, "day")` is one calendar day and twelve hours.
748
+ *
749
+ * @throws RangeError on a non-finite amount (NaN, ±Infinity, a non-number),
750
+ * which the native boundary would otherwise read as 0, and on a result
751
+ * outside years 0000-9999.
752
+ */
753
+ plus(amount: number, unit: DateUnit): DateTime;
754
+ /**
755
+ * Move by a duration, as Luxon's `plus(duration)`: whole years and months
756
+ * first (one step, so Feb 29 + 1 year 1 month is Mar 29), then whole weeks
757
+ * and days, both on the zone's calendar, then fractions and clock units as
758
+ * elapsed time.
759
+ */
760
+ plus(duration: Duration | DurationObject): DateTime;
761
+ plus(
762
+ amountOrDuration: number | Duration | DurationObject,
763
+ unit?: DateUnit,
764
+ ): DateTime {
765
+ if (typeof amountOrDuration === "object" && amountOrDuration !== null) {
766
+ return this.#plusDuration(
767
+ amountOrDuration instanceof Duration
768
+ ? amountOrDuration
769
+ : Duration.fromObject(amountOrDuration),
770
+ );
771
+ }
772
+ if (unit === undefined) {
773
+ throw new TypeError("plus(amount, unit) needs a unit");
774
+ }
775
+ return this.#plusUnit(amountOrDuration, unit);
776
+ }
777
+
778
+ #plusDuration(duration: Duration): DateTime {
779
+ const v = duration.toObject();
780
+ const months = Math.trunc(v.years) * 12 + Math.trunc(v.months);
781
+ const days = Math.trunc(v.weeks) * 7 + Math.trunc(v.days);
782
+ const elapsed = Duration.fromObject({
783
+ years: v.years - Math.trunc(v.years),
784
+ months: v.months - Math.trunc(v.months),
785
+ weeks: v.weeks - Math.trunc(v.weeks),
786
+ days: v.days - Math.trunc(v.days),
787
+ hours: v.hours,
788
+ minutes: v.minutes,
789
+ seconds: v.seconds,
790
+ milliseconds: v.milliseconds,
791
+ }).as("milliseconds");
792
+ let out: DateTime = this.#plusUnit(months, "month");
793
+ if (days !== 0) out = out.#plusUnit(days, "day");
794
+ if (elapsed === 0) return out;
795
+ return this.#derive(new Date(out.toMillis() + Math.round(elapsed)));
796
+ }
797
+
798
+ #plusUnit(amount: number, unit: DateUnit): DateTime {
799
+ if (typeof amount !== "number" || !Number.isFinite(amount)) {
800
+ throw new RangeError(
801
+ `Invalid unit value ${String(amount)}: plus/minus take a finite number`,
802
+ );
803
+ }
804
+ const unitMs = casualUnitMs(unit);
805
+ const whole = Math.trunc(amount);
806
+ if (!Number.isSafeInteger(whole)) {
807
+ throw new RangeError(
808
+ `plus(${amount}, '${unit}') is out of range: years are limited to 0000-9999`,
809
+ );
810
+ }
429
811
  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);
812
+ const shifted =
813
+ whole === 0
814
+ ? this.#iso
815
+ : this.#zone !== "UTC" && isCalendarUnit(unit)
816
+ ? n.addInZone(this.#iso, whole, unit, this.#zone)
817
+ : n.add(this.#iso, whole, unit);
818
+ const fraction = amount - whole;
819
+ if (fraction === 0) return this.#derive(shifted);
820
+ return this.#derive(
821
+ new Date(Date.parse(shifted) + Math.round(fraction * unitMs)),
822
+ );
823
+ }
824
+ minus(amount: number, unit: DateUnit): DateTime;
825
+ /** Move back by a duration — `plus` of its negation, as in Luxon. */
826
+ minus(duration: Duration | DurationObject): DateTime;
827
+ minus(
828
+ amountOrDuration: number | Duration | DurationObject,
829
+ unit?: DateUnit,
830
+ ): DateTime {
831
+ if (typeof amountOrDuration === "object" && amountOrDuration !== null) {
832
+ const duration =
833
+ amountOrDuration instanceof Duration
834
+ ? amountOrDuration
835
+ : Duration.fromObject(amountOrDuration);
836
+ return this.#plusDuration(duration.negate());
837
+ }
838
+ if (unit === undefined) {
839
+ throw new TypeError("minus(amount, unit) needs a unit");
840
+ }
841
+ // Checked before negating: `-"1"` would turn a string into a number.
842
+ if (typeof amountOrDuration !== "number") {
843
+ throw new RangeError(
844
+ `Invalid unit value ${String(amountOrDuration)}: plus/minus take a finite number`,
845
+ );
846
+ }
847
+ return this.#plusUnit(-amountOrDuration, unit);
435
848
  }
436
- minus(amount: number, unit: DateUnit): DateTime {
437
- return this.plus(-amount, unit);
849
+
850
+ /**
851
+ * `this - other` as a Duration in the given unit(s), as Luxon's `diff`:
852
+ * calendar units are counted on this value's calendar (a day across a DST
853
+ * change is one day), the lowest unit keeps its fraction, and clock units
854
+ * take what is left. `.as(unit)` reads it as a number.
855
+ */
856
+ diff(
857
+ other: DateInput,
858
+ unit:
859
+ | DateUnit
860
+ | DurationUnit
861
+ | "millisecond"
862
+ | ReadonlyArray<DateUnit | DurationUnit | "millisecond"> = "milliseconds",
863
+ ): Duration {
864
+ const units = (Array.isArray(unit) ? unit : [unit]).map(durationUnitOf);
865
+ const ordered = DIFF_ORDER.filter((u) => units.includes(u));
866
+ if (ordered.length === 0) throw new RangeError("diff needs a unit");
867
+ const o = DateTime.from(other).setZone(this.#zone);
868
+ const thisIsLater = this.toMillis() >= o.toMillis();
869
+ const earlier = thisIsLater ? o : this;
870
+ const later = thisIsLater ? this : o;
871
+
872
+ const calendar = ordered.filter((u) => CALENDAR_UNITS.has(u));
873
+ const clock = ordered.filter((u) => !CALENDAR_UNITS.has(u));
874
+ const results: DurationObject = {};
875
+ let cursor = earlier;
876
+ for (const u of calendar) {
877
+ results[u] = Math.trunc(later.#diffNumber(cursor, u));
878
+ cursor = earlier.plus(results);
879
+ }
880
+ let out: Duration;
881
+ const lowest = calendar.at(-1);
882
+ if (clock.length === 0 && lowest !== undefined) {
883
+ results[lowest] =
884
+ (results[lowest] ?? 0) + later.#diffNumber(cursor, lowest);
885
+ out = Duration.fromObject(results);
886
+ } else {
887
+ out = Duration.fromMillis(later.toMillis() - cursor.toMillis())
888
+ .shiftTo(...clock)
889
+ .plus(results);
890
+ }
891
+ return thisIsLater ? out : out.negate();
438
892
  }
439
893
 
440
- diff(other: DateInput, unit: DateUnit): number {
894
+ /** `this - other` in one unit, as a fractional number (calendar-aware). */
895
+ #diffNumber(other: DateTime, unit: DurationUnit): number {
441
896
  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);
897
+ const singular = unit.slice(0, -1);
898
+ return CALENDAR_UNITS.has(unit)
899
+ ? n.diffInZone(this.#iso, other.#iso, singular, this.#zone)
900
+ : n.diff(this.#iso, other.#iso, unit);
446
901
  }
447
902
 
448
903
  // ─── Comparison ─────────────────────────────────────────
449
904
 
905
+ /**
906
+ * Same instant — and, against another DateTime, same zone and locale, as
907
+ * Luxon's `equals`. Compare `toMillis()` (or use `<`, `>`) for the instant
908
+ * alone.
909
+ */
450
910
  equals(other: DateInput): boolean {
911
+ if (other instanceof DateTime) {
912
+ return (
913
+ this.#iso === other.#iso &&
914
+ this.#zone === other.#zone &&
915
+ this.#locale === other.#locale
916
+ );
917
+ }
451
918
  return this.#iso === toIso(other);
452
919
  }
453
920
  isBefore(other: DateInput): boolean {
@@ -456,10 +923,10 @@ export class DateTime {
456
923
  isAfter(other: DateInput): boolean {
457
924
  return toMs(this) > toMs(other);
458
925
  }
926
+ /** Whether `other` falls in the same `unit` as this value, on this value's calendar. */
459
927
  hasSame(other: DateInput, unit: BoundUnit): boolean {
460
- return (
461
- this.startOf(unit).toISO() === DateTime.from(other).startOf(unit).toISO()
462
- );
928
+ const o = DateTime.from(other).setZone(this.#zone);
929
+ return this.startOf(unit).toMillis() === o.startOf(unit).toMillis();
463
930
  }
464
931
  isSameDay(other: DateInput): boolean {
465
932
  return this.hasSame(other, "day");
@@ -477,22 +944,20 @@ export class DateTime {
477
944
  */
478
945
  startOf(unit: BoundUnit): DateTime {
479
946
  const n = nativeChronos();
480
- return new DateTime(
947
+ return this.#derive(
481
948
  this.#zone === "UTC"
482
949
  ? n.startOf(this.#iso, unit)
483
950
  : n.startOfInZone(this.#iso, unit, this.#zone),
484
- this.#zone,
485
951
  );
486
952
  }
487
953
 
488
954
  /** The last instant of `unit` — see {@link startOf} on the shared routine. */
489
955
  endOf(unit: BoundUnit): DateTime {
490
956
  const n = nativeChronos();
491
- return new DateTime(
957
+ return this.#derive(
492
958
  this.#zone === "UTC"
493
959
  ? n.endOf(this.#iso, unit)
494
960
  : n.endOfInZone(this.#iso, unit, this.#zone),
495
- this.#zone,
496
961
  );
497
962
  }
498
963
 
@@ -504,6 +969,11 @@ export class DateTime {
504
969
 
505
970
  // ─── Formatting ─────────────────────────────────────────
506
971
 
972
+ /**
973
+ * Format with chronos's moment-style tokens (`YYYY`, `YY`, `MM`, `DD`,
974
+ * `HH`, `mm`, `ss`, `Z`; `[text]` is literal) on this value's wall clock.
975
+ * Luxon's tokens (`yyyy`, `dd`, `LLL`, …) are {@link toFormat}.
976
+ */
507
977
  format(pattern = "YYYY-MM-DD HH:mm:ss"): string {
508
978
  if (this.#zone !== "UTC") {
509
979
  return formatFromIsoString(
@@ -514,21 +984,98 @@ export class DateTime {
514
984
  return nativeChronos().format(this.#iso, pattern);
515
985
  }
516
986
 
987
+ /**
988
+ * Format with Luxon's tokens (`yyyy-MM-dd HH:mm`, `dd LLL yyyy`, `EEEE`,
989
+ * `ZZ`, macros such as `DD` or `t`; `'quoted'` text is literal), on this
990
+ * value's wall clock. {@link format} keeps chronos's moment-style tokens.
991
+ */
992
+ toFormat(pattern: string): string {
993
+ return this.#luxonFormat(pattern, false);
994
+ }
995
+
996
+ /** `allowZ`: a UTC value writes its offset as `Z` (ISO and SQL output). */
997
+ #luxonFormat(pattern: string, allowZ = true): string {
998
+ return formatLuxon(pattern, {
999
+ parts: this.calendar,
1000
+ ts: this.toMillis(),
1001
+ offset: this.offset,
1002
+ zone: this.#zone,
1003
+ locale: this.#locale,
1004
+ allowZ: allowZ && this.#zone === "UTC",
1005
+ });
1006
+ }
1007
+
517
1008
  toDate(): Date {
518
1009
  return new Date(this.#iso);
519
1010
  }
520
- toISO(): string {
521
- return this.#iso;
1011
+
1012
+ /**
1013
+ * ISO 8601 on this value's wall clock, as Luxon's `toISO`: `…Z` in UTC,
1014
+ * the local offset (`2026-08-10T12:00:00.000+02:00`) in any other zone —
1015
+ * the same instant either way.
1016
+ */
1017
+ toISO(
1018
+ options: { suppressMilliseconds?: boolean; includeOffset?: boolean } = {},
1019
+ ): string {
1020
+ const plain =
1021
+ options.suppressMilliseconds !== true && options.includeOffset !== false;
1022
+ if (this.#zone === "UTC" && plain) return this.#iso;
1023
+ return this.#luxonFormat(`yyyy-MM-dd'T'${this.#timeFormat(options)}`);
1024
+ }
1025
+
1026
+ #timeFormat(options: {
1027
+ suppressMilliseconds?: boolean;
1028
+ includeOffset?: boolean;
1029
+ }): string {
1030
+ const ms =
1031
+ options.suppressMilliseconds === true && this.millisecond === 0
1032
+ ? ""
1033
+ : ".SSS";
1034
+ return `HH:mm:ss${ms}${options.includeOffset === false ? "" : "ZZ"}`;
1035
+ }
1036
+
1037
+ /** `yyyy-MM-dd` on this value's calendar. */
1038
+ toISODate(): string {
1039
+ return this.#luxonFormat("yyyy-MM-dd");
1040
+ }
1041
+
1042
+ /** `HH:mm:ss.SSS` plus the offset, on this value's wall clock. */
1043
+ toISOTime(
1044
+ options: { suppressMilliseconds?: boolean; includeOffset?: boolean } = {},
1045
+ ): string {
1046
+ return this.#luxonFormat(this.#timeFormat(options));
1047
+ }
1048
+
1049
+ /** `yyyy-MM-dd`, as SQL writes a date. */
1050
+ toSQLDate(): string {
1051
+ return this.toISODate();
1052
+ }
1053
+
1054
+ /** `HH:mm:ss.SSS +02:00` (`Z` in UTC), as Luxon's `toSQLTime`. */
1055
+ toSQLTime(options: { includeOffset?: boolean } = {}): string {
1056
+ return this.#luxonFormat(
1057
+ options.includeOffset === false ? "HH:mm:ss.SSS" : "HH:mm:ss.SSS ZZ",
1058
+ );
1059
+ }
1060
+
1061
+ /** `yyyy-MM-dd HH:mm:ss.SSS +02:00`, as Luxon's `toSQL`. */
1062
+ toSQL(options: { includeOffset?: boolean } = {}): string {
1063
+ return `${this.toSQLDate()} ${this.toSQLTime(options)}`;
522
1064
  }
1065
+
523
1066
  toString(): string {
524
- return this.#iso;
1067
+ return this.toISO();
525
1068
  }
526
1069
  toJSON(): string {
527
- return this.#iso;
1070
+ return this.toISO();
528
1071
  }
529
1072
  toMillis(): number {
530
1073
  return new Date(this.#iso).getTime();
531
1074
  }
1075
+ /** Epoch milliseconds, so `a < b` and `a - b` work as with Luxon. */
1076
+ valueOf(): number {
1077
+ return this.toMillis();
1078
+ }
532
1079
  toSeconds(): number {
533
1080
  return Math.floor(this.toMillis() / 1000);
534
1081
  }
@@ -537,8 +1084,10 @@ export class DateTime {
537
1084
  locale?: Intl.LocalesArgument,
538
1085
  options?: Intl.DateTimeFormatOptions,
539
1086
  ): string {
540
- return new Intl.DateTimeFormat(locale, {
541
- ...(this.#zone !== "UTC" ? { timeZone: this.#zone } : {}),
1087
+ // The value's own zone, UTC included: without it Intl falls back to the
1088
+ // host's zone and the same value prints differently per machine.
1089
+ return new Intl.DateTimeFormat(locale ?? this.#locale, {
1090
+ timeZone: this.#zone,
542
1091
  ...options,
543
1092
  }).format(this.toDate());
544
1093
  }
@@ -571,7 +1120,7 @@ export class DateTime {
571
1120
  unit = "year";
572
1121
  value = Math.round(diffMs / 31_536_000_000);
573
1122
  }
574
- return new Intl.RelativeTimeFormat(options?.locale as string | undefined, {
1123
+ return new Intl.RelativeTimeFormat(options?.locale, {
575
1124
  numeric: "auto",
576
1125
  }).format(value, unit);
577
1126
  }
@@ -584,7 +1133,7 @@ export class DateTime {
584
1133
  nativeChronos().toZone(this.#iso, this.#zone).iso,
585
1134
  );
586
1135
  }
587
- return nativeChronos().calendarParts(this.#iso) as CalendarParts;
1136
+ return nativeChronos().calendarParts(this.#iso);
588
1137
  }
589
1138
  get weekday(): number {
590
1139
  return this.calendar.weekday;