@nocobase/plugin-auth 0.17.0-alpha.7 → 0.18.0-alpha.2

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 (63) hide show
  1. package/dist/client/authenticator.d.ts +13 -0
  2. package/dist/client/basic/SignInForm.d.ts +9 -0
  3. package/dist/client/basic/SignUpForm.d.ts +13 -0
  4. package/dist/client/basic/index.d.ts +3 -0
  5. package/dist/client/index.d.ts +21 -0
  6. package/dist/client/index.js +12 -2
  7. package/dist/client/pages/AuthLayout.d.ts +2 -0
  8. package/dist/client/pages/SignInPage.d.ts +16 -0
  9. package/dist/client/pages/SignUpPage.d.ts +21 -0
  10. package/dist/client/pages/index.d.ts +3 -0
  11. package/dist/client/settings/Options.d.ts +3 -2
  12. package/dist/externalVersion.js +14 -12
  13. package/dist/locale/en-US.json +4 -1
  14. package/dist/locale/zh-CN.json +4 -1
  15. package/dist/node_modules/cron/LICENSE +0 -0
  16. package/dist/node_modules/cron/lib/cron.js +1 -1
  17. package/dist/node_modules/cron/lib/job.js +0 -0
  18. package/dist/node_modules/cron/lib/time.js +33 -20
  19. package/dist/node_modules/cron/node_modules/luxon/build/amd/luxon.js +7826 -0
  20. package/dist/node_modules/cron/node_modules/luxon/build/cjs-browser/luxon.js +7824 -0
  21. package/dist/node_modules/cron/node_modules/luxon/build/es6/luxon.js +7217 -0
  22. package/dist/node_modules/cron/node_modules/luxon/build/global/luxon.js +7829 -0
  23. package/dist/node_modules/cron/node_modules/luxon/build/global/luxon.min.js +1 -0
  24. package/dist/node_modules/cron/node_modules/luxon/build/node/luxon.js +6932 -0
  25. package/dist/node_modules/cron/node_modules/luxon/package.json +85 -0
  26. package/dist/node_modules/cron/node_modules/luxon/src/datetime.js +2248 -0
  27. package/dist/node_modules/cron/node_modules/luxon/src/duration.js +948 -0
  28. package/dist/node_modules/cron/node_modules/luxon/src/errors.js +61 -0
  29. package/dist/node_modules/cron/node_modules/luxon/src/impl/conversions.js +161 -0
  30. package/dist/node_modules/cron/node_modules/luxon/src/impl/diff.js +75 -0
  31. package/dist/node_modules/cron/node_modules/luxon/src/impl/digits.js +75 -0
  32. package/dist/node_modules/cron/node_modules/luxon/src/impl/english.js +233 -0
  33. package/dist/node_modules/cron/node_modules/luxon/src/impl/formats.js +176 -0
  34. package/dist/node_modules/cron/node_modules/luxon/src/impl/formatter.js +400 -0
  35. package/dist/node_modules/cron/node_modules/luxon/src/impl/invalid.js +14 -0
  36. package/dist/node_modules/cron/node_modules/luxon/src/impl/locale.js +494 -0
  37. package/dist/node_modules/cron/node_modules/luxon/src/impl/regexParser.js +335 -0
  38. package/dist/node_modules/cron/node_modules/luxon/src/impl/tokenParser.js +444 -0
  39. package/dist/node_modules/cron/node_modules/luxon/src/impl/util.js +274 -0
  40. package/dist/node_modules/cron/node_modules/luxon/src/impl/zoneUtil.js +34 -0
  41. package/dist/node_modules/cron/node_modules/luxon/src/info.js +169 -0
  42. package/dist/node_modules/cron/node_modules/luxon/src/interval.js +637 -0
  43. package/dist/node_modules/cron/node_modules/luxon/src/luxon.js +26 -0
  44. package/dist/node_modules/cron/node_modules/luxon/src/package.json +4 -0
  45. package/dist/node_modules/cron/node_modules/luxon/src/settings.js +148 -0
  46. package/dist/node_modules/cron/node_modules/luxon/src/zone.js +91 -0
  47. package/dist/node_modules/cron/node_modules/luxon/src/zones/IANAZone.js +189 -0
  48. package/dist/node_modules/cron/node_modules/luxon/src/zones/fixedOffsetZone.js +102 -0
  49. package/dist/node_modules/cron/node_modules/luxon/src/zones/invalidZone.js +53 -0
  50. package/dist/node_modules/cron/node_modules/luxon/src/zones/systemZone.js +61 -0
  51. package/dist/node_modules/cron/package.json +1 -1
  52. package/dist/node_modules/cron/types/index.d.ts +181 -0
  53. package/dist/node_modules/cron/types/index.test-d.ts +85 -0
  54. package/dist/server/actions/authenticators.js +3 -0
  55. package/dist/server/basic-auth.js +5 -2
  56. package/dist/server/migrations/20231218132032-fix-allow-signup.d.ts +5 -0
  57. package/dist/server/migrations/20231218132032-fix-allow-signup.js +54 -0
  58. package/dist/server/model/authenticator.d.ts +5 -2
  59. package/dist/server/model/authenticator.js +2 -2
  60. package/package.json +2 -2
  61. package/dist/client/AuthPluginProvider.d.ts +0 -2
  62. package/dist/client/basic/SigninPage.d.ts +0 -6
  63. package/dist/client/basic/SignupPage.d.ts +0 -5
@@ -0,0 +1,2248 @@
1
+ import Duration from "./duration.js";
2
+ import Interval from "./interval.js";
3
+ import Settings from "./settings.js";
4
+ import Info from "./info.js";
5
+ import Formatter from "./impl/formatter.js";
6
+ import FixedOffsetZone from "./zones/fixedOffsetZone.js";
7
+ import Locale from "./impl/locale.js";
8
+ import {
9
+ isUndefined,
10
+ maybeArray,
11
+ isDate,
12
+ isNumber,
13
+ bestBy,
14
+ daysInMonth,
15
+ daysInYear,
16
+ isLeapYear,
17
+ weeksInWeekYear,
18
+ normalizeObject,
19
+ roundTo,
20
+ objToLocalTS,
21
+ padStart,
22
+ } from "./impl/util.js";
23
+ import { normalizeZone } from "./impl/zoneUtil.js";
24
+ import diff from "./impl/diff.js";
25
+ import { parseRFC2822Date, parseISODate, parseHTTPDate, parseSQL } from "./impl/regexParser.js";
26
+ import {
27
+ parseFromTokens,
28
+ explainFromTokens,
29
+ formatOptsToTokens,
30
+ expandMacroTokens,
31
+ } from "./impl/tokenParser.js";
32
+ import {
33
+ gregorianToWeek,
34
+ weekToGregorian,
35
+ gregorianToOrdinal,
36
+ ordinalToGregorian,
37
+ hasInvalidGregorianData,
38
+ hasInvalidWeekData,
39
+ hasInvalidOrdinalData,
40
+ hasInvalidTimeData,
41
+ } from "./impl/conversions.js";
42
+ import * as Formats from "./impl/formats.js";
43
+ import {
44
+ InvalidArgumentError,
45
+ ConflictingSpecificationError,
46
+ InvalidUnitError,
47
+ InvalidDateTimeError,
48
+ } from "./errors.js";
49
+ import Invalid from "./impl/invalid.js";
50
+
51
+ const INVALID = "Invalid DateTime";
52
+ const MAX_DATE = 8.64e15;
53
+
54
+ function unsupportedZone(zone) {
55
+ return new Invalid("unsupported zone", `the zone "${zone.name}" is not supported`);
56
+ }
57
+
58
+ // we cache week data on the DT object and this intermediates the cache
59
+ function possiblyCachedWeekData(dt) {
60
+ if (dt.weekData === null) {
61
+ dt.weekData = gregorianToWeek(dt.c);
62
+ }
63
+ return dt.weekData;
64
+ }
65
+
66
+ // clone really means, "make a new object with these modifications". all "setters" really use this
67
+ // to create a new object while only changing some of the properties
68
+ function clone(inst, alts) {
69
+ const current = {
70
+ ts: inst.ts,
71
+ zone: inst.zone,
72
+ c: inst.c,
73
+ o: inst.o,
74
+ loc: inst.loc,
75
+ invalid: inst.invalid,
76
+ };
77
+ return new DateTime({ ...current, ...alts, old: current });
78
+ }
79
+
80
+ // find the right offset a given local time. The o input is our guess, which determines which
81
+ // offset we'll pick in ambiguous cases (e.g. there are two 3 AMs b/c Fallback DST)
82
+ function fixOffset(localTS, o, tz) {
83
+ // Our UTC time is just a guess because our offset is just a guess
84
+ let utcGuess = localTS - o * 60 * 1000;
85
+
86
+ // Test whether the zone matches the offset for this ts
87
+ const o2 = tz.offset(utcGuess);
88
+
89
+ // If so, offset didn't change and we're done
90
+ if (o === o2) {
91
+ return [utcGuess, o];
92
+ }
93
+
94
+ // If not, change the ts by the difference in the offset
95
+ utcGuess -= (o2 - o) * 60 * 1000;
96
+
97
+ // If that gives us the local time we want, we're done
98
+ const o3 = tz.offset(utcGuess);
99
+ if (o2 === o3) {
100
+ return [utcGuess, o2];
101
+ }
102
+
103
+ // If it's different, we're in a hole time. The offset has changed, but the we don't adjust the time
104
+ return [localTS - Math.min(o2, o3) * 60 * 1000, Math.max(o2, o3)];
105
+ }
106
+
107
+ // convert an epoch timestamp into a calendar object with the given offset
108
+ function tsToObj(ts, offset) {
109
+ ts += offset * 60 * 1000;
110
+
111
+ const d = new Date(ts);
112
+
113
+ return {
114
+ year: d.getUTCFullYear(),
115
+ month: d.getUTCMonth() + 1,
116
+ day: d.getUTCDate(),
117
+ hour: d.getUTCHours(),
118
+ minute: d.getUTCMinutes(),
119
+ second: d.getUTCSeconds(),
120
+ millisecond: d.getUTCMilliseconds(),
121
+ };
122
+ }
123
+
124
+ // convert a calendar object to a epoch timestamp
125
+ function objToTS(obj, offset, zone) {
126
+ return fixOffset(objToLocalTS(obj), offset, zone);
127
+ }
128
+
129
+ // create a new DT instance by adding a duration, adjusting for DSTs
130
+ function adjustTime(inst, dur) {
131
+ const oPre = inst.o,
132
+ year = inst.c.year + Math.trunc(dur.years),
133
+ month = inst.c.month + Math.trunc(dur.months) + Math.trunc(dur.quarters) * 3,
134
+ c = {
135
+ ...inst.c,
136
+ year,
137
+ month,
138
+ day:
139
+ Math.min(inst.c.day, daysInMonth(year, month)) +
140
+ Math.trunc(dur.days) +
141
+ Math.trunc(dur.weeks) * 7,
142
+ },
143
+ millisToAdd = Duration.fromObject({
144
+ years: dur.years - Math.trunc(dur.years),
145
+ quarters: dur.quarters - Math.trunc(dur.quarters),
146
+ months: dur.months - Math.trunc(dur.months),
147
+ weeks: dur.weeks - Math.trunc(dur.weeks),
148
+ days: dur.days - Math.trunc(dur.days),
149
+ hours: dur.hours,
150
+ minutes: dur.minutes,
151
+ seconds: dur.seconds,
152
+ milliseconds: dur.milliseconds,
153
+ }).as("milliseconds"),
154
+ localTS = objToLocalTS(c);
155
+
156
+ let [ts, o] = fixOffset(localTS, oPre, inst.zone);
157
+
158
+ if (millisToAdd !== 0) {
159
+ ts += millisToAdd;
160
+ // that could have changed the offset by going over a DST, but we want to keep the ts the same
161
+ o = inst.zone.offset(ts);
162
+ }
163
+
164
+ return { ts, o };
165
+ }
166
+
167
+ // helper useful in turning the results of parsing into real dates
168
+ // by handling the zone options
169
+ function parseDataToDateTime(parsed, parsedZone, opts, format, text, specificOffset) {
170
+ const { setZone, zone } = opts;
171
+ if ((parsed && Object.keys(parsed).length !== 0) || parsedZone) {
172
+ const interpretationZone = parsedZone || zone,
173
+ inst = DateTime.fromObject(parsed, {
174
+ ...opts,
175
+ zone: interpretationZone,
176
+ specificOffset,
177
+ });
178
+ return setZone ? inst : inst.setZone(zone);
179
+ } else {
180
+ return DateTime.invalid(
181
+ new Invalid("unparsable", `the input "${text}" can't be parsed as ${format}`)
182
+ );
183
+ }
184
+ }
185
+
186
+ // if you want to output a technical format (e.g. RFC 2822), this helper
187
+ // helps handle the details
188
+ function toTechFormat(dt, format, allowZ = true) {
189
+ return dt.isValid
190
+ ? Formatter.create(Locale.create("en-US"), {
191
+ allowZ,
192
+ forceSimple: true,
193
+ }).formatDateTimeFromString(dt, format)
194
+ : null;
195
+ }
196
+
197
+ function toISODate(o, extended) {
198
+ const longFormat = o.c.year > 9999 || o.c.year < 0;
199
+ let c = "";
200
+ if (longFormat && o.c.year >= 0) c += "+";
201
+ c += padStart(o.c.year, longFormat ? 6 : 4);
202
+
203
+ if (extended) {
204
+ c += "-";
205
+ c += padStart(o.c.month);
206
+ c += "-";
207
+ c += padStart(o.c.day);
208
+ } else {
209
+ c += padStart(o.c.month);
210
+ c += padStart(o.c.day);
211
+ }
212
+ return c;
213
+ }
214
+
215
+ function toISOTime(
216
+ o,
217
+ extended,
218
+ suppressSeconds,
219
+ suppressMilliseconds,
220
+ includeOffset,
221
+ extendedZone
222
+ ) {
223
+ let c = padStart(o.c.hour);
224
+ if (extended) {
225
+ c += ":";
226
+ c += padStart(o.c.minute);
227
+ if (o.c.second !== 0 || !suppressSeconds) {
228
+ c += ":";
229
+ }
230
+ } else {
231
+ c += padStart(o.c.minute);
232
+ }
233
+
234
+ if (o.c.second !== 0 || !suppressSeconds) {
235
+ c += padStart(o.c.second);
236
+
237
+ if (o.c.millisecond !== 0 || !suppressMilliseconds) {
238
+ c += ".";
239
+ c += padStart(o.c.millisecond, 3);
240
+ }
241
+ }
242
+
243
+ if (includeOffset) {
244
+ if (o.isOffsetFixed && o.offset === 0 && !extendedZone) {
245
+ c += "Z";
246
+ } else if (o.o < 0) {
247
+ c += "-";
248
+ c += padStart(Math.trunc(-o.o / 60));
249
+ c += ":";
250
+ c += padStart(Math.trunc(-o.o % 60));
251
+ } else {
252
+ c += "+";
253
+ c += padStart(Math.trunc(o.o / 60));
254
+ c += ":";
255
+ c += padStart(Math.trunc(o.o % 60));
256
+ }
257
+ }
258
+
259
+ if (extendedZone) {
260
+ c += "[" + o.zone.ianaName + "]";
261
+ }
262
+ return c;
263
+ }
264
+
265
+ // defaults for unspecified units in the supported calendars
266
+ const defaultUnitValues = {
267
+ month: 1,
268
+ day: 1,
269
+ hour: 0,
270
+ minute: 0,
271
+ second: 0,
272
+ millisecond: 0,
273
+ },
274
+ defaultWeekUnitValues = {
275
+ weekNumber: 1,
276
+ weekday: 1,
277
+ hour: 0,
278
+ minute: 0,
279
+ second: 0,
280
+ millisecond: 0,
281
+ },
282
+ defaultOrdinalUnitValues = {
283
+ ordinal: 1,
284
+ hour: 0,
285
+ minute: 0,
286
+ second: 0,
287
+ millisecond: 0,
288
+ };
289
+
290
+ // Units in the supported calendars, sorted by bigness
291
+ const orderedUnits = ["year", "month", "day", "hour", "minute", "second", "millisecond"],
292
+ orderedWeekUnits = [
293
+ "weekYear",
294
+ "weekNumber",
295
+ "weekday",
296
+ "hour",
297
+ "minute",
298
+ "second",
299
+ "millisecond",
300
+ ],
301
+ orderedOrdinalUnits = ["year", "ordinal", "hour", "minute", "second", "millisecond"];
302
+
303
+ // standardize case and plurality in units
304
+ function normalizeUnit(unit) {
305
+ const normalized = {
306
+ year: "year",
307
+ years: "year",
308
+ month: "month",
309
+ months: "month",
310
+ day: "day",
311
+ days: "day",
312
+ hour: "hour",
313
+ hours: "hour",
314
+ minute: "minute",
315
+ minutes: "minute",
316
+ quarter: "quarter",
317
+ quarters: "quarter",
318
+ second: "second",
319
+ seconds: "second",
320
+ millisecond: "millisecond",
321
+ milliseconds: "millisecond",
322
+ weekday: "weekday",
323
+ weekdays: "weekday",
324
+ weeknumber: "weekNumber",
325
+ weeksnumber: "weekNumber",
326
+ weeknumbers: "weekNumber",
327
+ weekyear: "weekYear",
328
+ weekyears: "weekYear",
329
+ ordinal: "ordinal",
330
+ }[unit.toLowerCase()];
331
+
332
+ if (!normalized) throw new InvalidUnitError(unit);
333
+
334
+ return normalized;
335
+ }
336
+
337
+ // this is a dumbed down version of fromObject() that runs about 60% faster
338
+ // but doesn't do any validation, makes a bunch of assumptions about what units
339
+ // are present, and so on.
340
+ function quickDT(obj, opts) {
341
+ const zone = normalizeZone(opts.zone, Settings.defaultZone),
342
+ loc = Locale.fromObject(opts),
343
+ tsNow = Settings.now();
344
+
345
+ let ts, o;
346
+
347
+ // assume we have the higher-order units
348
+ if (!isUndefined(obj.year)) {
349
+ for (const u of orderedUnits) {
350
+ if (isUndefined(obj[u])) {
351
+ obj[u] = defaultUnitValues[u];
352
+ }
353
+ }
354
+
355
+ const invalid = hasInvalidGregorianData(obj) || hasInvalidTimeData(obj);
356
+ if (invalid) {
357
+ return DateTime.invalid(invalid);
358
+ }
359
+
360
+ const offsetProvis = zone.offset(tsNow);
361
+ [ts, o] = objToTS(obj, offsetProvis, zone);
362
+ } else {
363
+ ts = tsNow;
364
+ }
365
+
366
+ return new DateTime({ ts, zone, loc, o });
367
+ }
368
+
369
+ function diffRelative(start, end, opts) {
370
+ const round = isUndefined(opts.round) ? true : opts.round,
371
+ format = (c, unit) => {
372
+ c = roundTo(c, round || opts.calendary ? 0 : 2, true);
373
+ const formatter = end.loc.clone(opts).relFormatter(opts);
374
+ return formatter.format(c, unit);
375
+ },
376
+ differ = (unit) => {
377
+ if (opts.calendary) {
378
+ if (!end.hasSame(start, unit)) {
379
+ return end.startOf(unit).diff(start.startOf(unit), unit).get(unit);
380
+ } else return 0;
381
+ } else {
382
+ return end.diff(start, unit).get(unit);
383
+ }
384
+ };
385
+
386
+ if (opts.unit) {
387
+ return format(differ(opts.unit), opts.unit);
388
+ }
389
+
390
+ for (const unit of opts.units) {
391
+ const count = differ(unit);
392
+ if (Math.abs(count) >= 1) {
393
+ return format(count, unit);
394
+ }
395
+ }
396
+ return format(start > end ? -0 : 0, opts.units[opts.units.length - 1]);
397
+ }
398
+
399
+ function lastOpts(argList) {
400
+ let opts = {},
401
+ args;
402
+ if (argList.length > 0 && typeof argList[argList.length - 1] === "object") {
403
+ opts = argList[argList.length - 1];
404
+ args = Array.from(argList).slice(0, argList.length - 1);
405
+ } else {
406
+ args = Array.from(argList);
407
+ }
408
+ return [opts, args];
409
+ }
410
+
411
+ /**
412
+ * A DateTime is an immutable data structure representing a specific date and time and accompanying methods. It contains class and instance methods for creating, parsing, interrogating, transforming, and formatting them.
413
+ *
414
+ * A DateTime comprises of:
415
+ * * A timestamp. Each DateTime instance refers to a specific millisecond of the Unix epoch.
416
+ * * A time zone. Each instance is considered in the context of a specific zone (by default the local system's zone).
417
+ * * Configuration properties that effect how output strings are formatted, such as `locale`, `numberingSystem`, and `outputCalendar`.
418
+ *
419
+ * Here is a brief overview of the most commonly used functionality it provides:
420
+ *
421
+ * * **Creation**: To create a DateTime from its components, use one of its factory class methods: {@link DateTime.local}, {@link DateTime.utc}, and (most flexibly) {@link DateTime.fromObject}. To create one from a standard string format, use {@link DateTime.fromISO}, {@link DateTime.fromHTTP}, and {@link DateTime.fromRFC2822}. To create one from a custom string format, use {@link DateTime.fromFormat}. To create one from a native JS date, use {@link DateTime.fromJSDate}.
422
+ * * **Gregorian calendar and time**: To examine the Gregorian properties of a DateTime individually (i.e as opposed to collectively through {@link DateTime#toObject}), use the {@link DateTime#year}, {@link DateTime#month},
423
+ * {@link DateTime#day}, {@link DateTime#hour}, {@link DateTime#minute}, {@link DateTime#second}, {@link DateTime#millisecond} accessors.
424
+ * * **Week calendar**: For ISO week calendar attributes, see the {@link DateTime#weekYear}, {@link DateTime#weekNumber}, and {@link DateTime#weekday} accessors.
425
+ * * **Configuration** See the {@link DateTime#locale} and {@link DateTime#numberingSystem} accessors.
426
+ * * **Transformation**: To transform the DateTime into other DateTimes, use {@link DateTime#set}, {@link DateTime#reconfigure}, {@link DateTime#setZone}, {@link DateTime#setLocale}, {@link DateTime.plus}, {@link DateTime#minus}, {@link DateTime#endOf}, {@link DateTime#startOf}, {@link DateTime#toUTC}, and {@link DateTime#toLocal}.
427
+ * * **Output**: To convert the DateTime to other representations, use the {@link DateTime#toRelative}, {@link DateTime#toRelativeCalendar}, {@link DateTime#toJSON}, {@link DateTime#toISO}, {@link DateTime#toHTTP}, {@link DateTime#toObject}, {@link DateTime#toRFC2822}, {@link DateTime#toString}, {@link DateTime#toLocaleString}, {@link DateTime#toFormat}, {@link DateTime#toMillis} and {@link DateTime#toJSDate}.
428
+ *
429
+ * There's plenty others documented below. In addition, for more information on subtler topics like internationalization, time zones, alternative calendars, validity, and so on, see the external documentation.
430
+ */
431
+ export default class DateTime {
432
+ /**
433
+ * @access private
434
+ */
435
+ constructor(config) {
436
+ const zone = config.zone || Settings.defaultZone;
437
+
438
+ let invalid =
439
+ config.invalid ||
440
+ (Number.isNaN(config.ts) ? new Invalid("invalid input") : null) ||
441
+ (!zone.isValid ? unsupportedZone(zone) : null);
442
+ /**
443
+ * @access private
444
+ */
445
+ this.ts = isUndefined(config.ts) ? Settings.now() : config.ts;
446
+
447
+ let c = null,
448
+ o = null;
449
+ if (!invalid) {
450
+ const unchanged = config.old && config.old.ts === this.ts && config.old.zone.equals(zone);
451
+
452
+ if (unchanged) {
453
+ [c, o] = [config.old.c, config.old.o];
454
+ } else {
455
+ const ot = zone.offset(this.ts);
456
+ c = tsToObj(this.ts, ot);
457
+ invalid = Number.isNaN(c.year) ? new Invalid("invalid input") : null;
458
+ c = invalid ? null : c;
459
+ o = invalid ? null : ot;
460
+ }
461
+ }
462
+
463
+ /**
464
+ * @access private
465
+ */
466
+ this._zone = zone;
467
+ /**
468
+ * @access private
469
+ */
470
+ this.loc = config.loc || Locale.create();
471
+ /**
472
+ * @access private
473
+ */
474
+ this.invalid = invalid;
475
+ /**
476
+ * @access private
477
+ */
478
+ this.weekData = null;
479
+ /**
480
+ * @access private
481
+ */
482
+ this.c = c;
483
+ /**
484
+ * @access private
485
+ */
486
+ this.o = o;
487
+ /**
488
+ * @access private
489
+ */
490
+ this.isLuxonDateTime = true;
491
+ }
492
+
493
+ // CONSTRUCT
494
+
495
+ /**
496
+ * Create a DateTime for the current instant, in the system's time zone.
497
+ *
498
+ * Use Settings to override these default values if needed.
499
+ * @example DateTime.now().toISO() //~> now in the ISO format
500
+ * @return {DateTime}
501
+ */
502
+ static now() {
503
+ return new DateTime({});
504
+ }
505
+
506
+ /**
507
+ * Create a local DateTime
508
+ * @param {number} [year] - The calendar year. If omitted (as in, call `local()` with no arguments), the current time will be used
509
+ * @param {number} [month=1] - The month, 1-indexed
510
+ * @param {number} [day=1] - The day of the month, 1-indexed
511
+ * @param {number} [hour=0] - The hour of the day, in 24-hour time
512
+ * @param {number} [minute=0] - The minute of the hour, meaning a number between 0 and 59
513
+ * @param {number} [second=0] - The second of the minute, meaning a number between 0 and 59
514
+ * @param {number} [millisecond=0] - The millisecond of the second, meaning a number between 0 and 999
515
+ * @example DateTime.local() //~> now
516
+ * @example DateTime.local({ zone: "America/New_York" }) //~> now, in US east coast time
517
+ * @example DateTime.local(2017) //~> 2017-01-01T00:00:00
518
+ * @example DateTime.local(2017, 3) //~> 2017-03-01T00:00:00
519
+ * @example DateTime.local(2017, 3, 12, { locale: "fr" }) //~> 2017-03-12T00:00:00, with a French locale
520
+ * @example DateTime.local(2017, 3, 12, 5) //~> 2017-03-12T05:00:00
521
+ * @example DateTime.local(2017, 3, 12, 5, { zone: "utc" }) //~> 2017-03-12T05:00:00, in UTC
522
+ * @example DateTime.local(2017, 3, 12, 5, 45) //~> 2017-03-12T05:45:00
523
+ * @example DateTime.local(2017, 3, 12, 5, 45, 10) //~> 2017-03-12T05:45:10
524
+ * @example DateTime.local(2017, 3, 12, 5, 45, 10, 765) //~> 2017-03-12T05:45:10.765
525
+ * @return {DateTime}
526
+ */
527
+ static local() {
528
+ const [opts, args] = lastOpts(arguments),
529
+ [year, month, day, hour, minute, second, millisecond] = args;
530
+ return quickDT({ year, month, day, hour, minute, second, millisecond }, opts);
531
+ }
532
+
533
+ /**
534
+ * Create a DateTime in UTC
535
+ * @param {number} [year] - The calendar year. If omitted (as in, call `utc()` with no arguments), the current time will be used
536
+ * @param {number} [month=1] - The month, 1-indexed
537
+ * @param {number} [day=1] - The day of the month
538
+ * @param {number} [hour=0] - The hour of the day, in 24-hour time
539
+ * @param {number} [minute=0] - The minute of the hour, meaning a number between 0 and 59
540
+ * @param {number} [second=0] - The second of the minute, meaning a number between 0 and 59
541
+ * @param {number} [millisecond=0] - The millisecond of the second, meaning a number between 0 and 999
542
+ * @param {Object} options - configuration options for the DateTime
543
+ * @param {string} [options.locale] - a locale to set on the resulting DateTime instance
544
+ * @param {string} [options.outputCalendar] - the output calendar to set on the resulting DateTime instance
545
+ * @param {string} [options.numberingSystem] - the numbering system to set on the resulting DateTime instance
546
+ * @example DateTime.utc() //~> now
547
+ * @example DateTime.utc(2017) //~> 2017-01-01T00:00:00Z
548
+ * @example DateTime.utc(2017, 3) //~> 2017-03-01T00:00:00Z
549
+ * @example DateTime.utc(2017, 3, 12) //~> 2017-03-12T00:00:00Z
550
+ * @example DateTime.utc(2017, 3, 12, 5) //~> 2017-03-12T05:00:00Z
551
+ * @example DateTime.utc(2017, 3, 12, 5, 45) //~> 2017-03-12T05:45:00Z
552
+ * @example DateTime.utc(2017, 3, 12, 5, 45, { locale: "fr" }) //~> 2017-03-12T05:45:00Z with a French locale
553
+ * @example DateTime.utc(2017, 3, 12, 5, 45, 10) //~> 2017-03-12T05:45:10Z
554
+ * @example DateTime.utc(2017, 3, 12, 5, 45, 10, 765, { locale: "fr" }) //~> 2017-03-12T05:45:10.765Z with a French locale
555
+ * @return {DateTime}
556
+ */
557
+ static utc() {
558
+ const [opts, args] = lastOpts(arguments),
559
+ [year, month, day, hour, minute, second, millisecond] = args;
560
+
561
+ opts.zone = FixedOffsetZone.utcInstance;
562
+ return quickDT({ year, month, day, hour, minute, second, millisecond }, opts);
563
+ }
564
+
565
+ /**
566
+ * Create a DateTime from a JavaScript Date object. Uses the default zone.
567
+ * @param {Date} date - a JavaScript Date object
568
+ * @param {Object} options - configuration options for the DateTime
569
+ * @param {string|Zone} [options.zone='local'] - the zone to place the DateTime into
570
+ * @return {DateTime}
571
+ */
572
+ static fromJSDate(date, options = {}) {
573
+ const ts = isDate(date) ? date.valueOf() : NaN;
574
+ if (Number.isNaN(ts)) {
575
+ return DateTime.invalid("invalid input");
576
+ }
577
+
578
+ const zoneToUse = normalizeZone(options.zone, Settings.defaultZone);
579
+ if (!zoneToUse.isValid) {
580
+ return DateTime.invalid(unsupportedZone(zoneToUse));
581
+ }
582
+
583
+ return new DateTime({
584
+ ts: ts,
585
+ zone: zoneToUse,
586
+ loc: Locale.fromObject(options),
587
+ });
588
+ }
589
+
590
+ /**
591
+ * Create a DateTime from a number of milliseconds since the epoch (meaning since 1 January 1970 00:00:00 UTC). Uses the default zone.
592
+ * @param {number} milliseconds - a number of milliseconds since 1970 UTC
593
+ * @param {Object} options - configuration options for the DateTime
594
+ * @param {string|Zone} [options.zone='local'] - the zone to place the DateTime into
595
+ * @param {string} [options.locale] - a locale to set on the resulting DateTime instance
596
+ * @param {string} options.outputCalendar - the output calendar to set on the resulting DateTime instance
597
+ * @param {string} options.numberingSystem - the numbering system to set on the resulting DateTime instance
598
+ * @return {DateTime}
599
+ */
600
+ static fromMillis(milliseconds, options = {}) {
601
+ if (!isNumber(milliseconds)) {
602
+ throw new InvalidArgumentError(
603
+ `fromMillis requires a numerical input, but received a ${typeof milliseconds} with value ${milliseconds}`
604
+ );
605
+ } else if (milliseconds < -MAX_DATE || milliseconds > MAX_DATE) {
606
+ // this isn't perfect because because we can still end up out of range because of additional shifting, but it's a start
607
+ return DateTime.invalid("Timestamp out of range");
608
+ } else {
609
+ return new DateTime({
610
+ ts: milliseconds,
611
+ zone: normalizeZone(options.zone, Settings.defaultZone),
612
+ loc: Locale.fromObject(options),
613
+ });
614
+ }
615
+ }
616
+
617
+ /**
618
+ * Create a DateTime from a number of seconds since the epoch (meaning since 1 January 1970 00:00:00 UTC). Uses the default zone.
619
+ * @param {number} seconds - a number of seconds since 1970 UTC
620
+ * @param {Object} options - configuration options for the DateTime
621
+ * @param {string|Zone} [options.zone='local'] - the zone to place the DateTime into
622
+ * @param {string} [options.locale] - a locale to set on the resulting DateTime instance
623
+ * @param {string} options.outputCalendar - the output calendar to set on the resulting DateTime instance
624
+ * @param {string} options.numberingSystem - the numbering system to set on the resulting DateTime instance
625
+ * @return {DateTime}
626
+ */
627
+ static fromSeconds(seconds, options = {}) {
628
+ if (!isNumber(seconds)) {
629
+ throw new InvalidArgumentError("fromSeconds requires a numerical input");
630
+ } else {
631
+ return new DateTime({
632
+ ts: seconds * 1000,
633
+ zone: normalizeZone(options.zone, Settings.defaultZone),
634
+ loc: Locale.fromObject(options),
635
+ });
636
+ }
637
+ }
638
+
639
+ /**
640
+ * Create a DateTime from a JavaScript object with keys like 'year' and 'hour' with reasonable defaults.
641
+ * @param {Object} obj - the object to create the DateTime from
642
+ * @param {number} obj.year - a year, such as 1987
643
+ * @param {number} obj.month - a month, 1-12
644
+ * @param {number} obj.day - a day of the month, 1-31, depending on the month
645
+ * @param {number} obj.ordinal - day of the year, 1-365 or 366
646
+ * @param {number} obj.weekYear - an ISO week year
647
+ * @param {number} obj.weekNumber - an ISO week number, between 1 and 52 or 53, depending on the year
648
+ * @param {number} obj.weekday - an ISO weekday, 1-7, where 1 is Monday and 7 is Sunday
649
+ * @param {number} obj.hour - hour of the day, 0-23
650
+ * @param {number} obj.minute - minute of the hour, 0-59
651
+ * @param {number} obj.second - second of the minute, 0-59
652
+ * @param {number} obj.millisecond - millisecond of the second, 0-999
653
+ * @param {Object} opts - options for creating this DateTime
654
+ * @param {string|Zone} [opts.zone='local'] - interpret the numbers in the context of a particular zone. Can take any value taken as the first argument to setZone()
655
+ * @param {string} [opts.locale='system's locale'] - a locale to set on the resulting DateTime instance
656
+ * @param {string} opts.outputCalendar - the output calendar to set on the resulting DateTime instance
657
+ * @param {string} opts.numberingSystem - the numbering system to set on the resulting DateTime instance
658
+ * @example DateTime.fromObject({ year: 1982, month: 5, day: 25}).toISODate() //=> '1982-05-25'
659
+ * @example DateTime.fromObject({ year: 1982 }).toISODate() //=> '1982-01-01'
660
+ * @example DateTime.fromObject({ hour: 10, minute: 26, second: 6 }) //~> today at 10:26:06
661
+ * @example DateTime.fromObject({ hour: 10, minute: 26, second: 6 }, { zone: 'utc' }),
662
+ * @example DateTime.fromObject({ hour: 10, minute: 26, second: 6 }, { zone: 'local' })
663
+ * @example DateTime.fromObject({ hour: 10, minute: 26, second: 6 }, { zone: 'America/New_York' })
664
+ * @example DateTime.fromObject({ weekYear: 2016, weekNumber: 2, weekday: 3 }).toISODate() //=> '2016-01-13'
665
+ * @return {DateTime}
666
+ */
667
+ static fromObject(obj, opts = {}) {
668
+ obj = obj || {};
669
+ const zoneToUse = normalizeZone(opts.zone, Settings.defaultZone);
670
+ if (!zoneToUse.isValid) {
671
+ return DateTime.invalid(unsupportedZone(zoneToUse));
672
+ }
673
+
674
+ const tsNow = Settings.now(),
675
+ offsetProvis = !isUndefined(opts.specificOffset)
676
+ ? opts.specificOffset
677
+ : zoneToUse.offset(tsNow),
678
+ normalized = normalizeObject(obj, normalizeUnit),
679
+ containsOrdinal = !isUndefined(normalized.ordinal),
680
+ containsGregorYear = !isUndefined(normalized.year),
681
+ containsGregorMD = !isUndefined(normalized.month) || !isUndefined(normalized.day),
682
+ containsGregor = containsGregorYear || containsGregorMD,
683
+ definiteWeekDef = normalized.weekYear || normalized.weekNumber,
684
+ loc = Locale.fromObject(opts);
685
+
686
+ // cases:
687
+ // just a weekday -> this week's instance of that weekday, no worries
688
+ // (gregorian data or ordinal) + (weekYear or weekNumber) -> error
689
+ // (gregorian month or day) + ordinal -> error
690
+ // otherwise just use weeks or ordinals or gregorian, depending on what's specified
691
+
692
+ if ((containsGregor || containsOrdinal) && definiteWeekDef) {
693
+ throw new ConflictingSpecificationError(
694
+ "Can't mix weekYear/weekNumber units with year/month/day or ordinals"
695
+ );
696
+ }
697
+
698
+ if (containsGregorMD && containsOrdinal) {
699
+ throw new ConflictingSpecificationError("Can't mix ordinal dates with month/day");
700
+ }
701
+
702
+ const useWeekData = definiteWeekDef || (normalized.weekday && !containsGregor);
703
+
704
+ // configure ourselves to deal with gregorian dates or week stuff
705
+ let units,
706
+ defaultValues,
707
+ objNow = tsToObj(tsNow, offsetProvis);
708
+ if (useWeekData) {
709
+ units = orderedWeekUnits;
710
+ defaultValues = defaultWeekUnitValues;
711
+ objNow = gregorianToWeek(objNow);
712
+ } else if (containsOrdinal) {
713
+ units = orderedOrdinalUnits;
714
+ defaultValues = defaultOrdinalUnitValues;
715
+ objNow = gregorianToOrdinal(objNow);
716
+ } else {
717
+ units = orderedUnits;
718
+ defaultValues = defaultUnitValues;
719
+ }
720
+
721
+ // set default values for missing stuff
722
+ let foundFirst = false;
723
+ for (const u of units) {
724
+ const v = normalized[u];
725
+ if (!isUndefined(v)) {
726
+ foundFirst = true;
727
+ } else if (foundFirst) {
728
+ normalized[u] = defaultValues[u];
729
+ } else {
730
+ normalized[u] = objNow[u];
731
+ }
732
+ }
733
+
734
+ // make sure the values we have are in range
735
+ const higherOrderInvalid = useWeekData
736
+ ? hasInvalidWeekData(normalized)
737
+ : containsOrdinal
738
+ ? hasInvalidOrdinalData(normalized)
739
+ : hasInvalidGregorianData(normalized),
740
+ invalid = higherOrderInvalid || hasInvalidTimeData(normalized);
741
+
742
+ if (invalid) {
743
+ return DateTime.invalid(invalid);
744
+ }
745
+
746
+ // compute the actual time
747
+ const gregorian = useWeekData
748
+ ? weekToGregorian(normalized)
749
+ : containsOrdinal
750
+ ? ordinalToGregorian(normalized)
751
+ : normalized,
752
+ [tsFinal, offsetFinal] = objToTS(gregorian, offsetProvis, zoneToUse),
753
+ inst = new DateTime({
754
+ ts: tsFinal,
755
+ zone: zoneToUse,
756
+ o: offsetFinal,
757
+ loc,
758
+ });
759
+
760
+ // gregorian data + weekday serves only to validate
761
+ if (normalized.weekday && containsGregor && obj.weekday !== inst.weekday) {
762
+ return DateTime.invalid(
763
+ "mismatched weekday",
764
+ `you can't specify both a weekday of ${normalized.weekday} and a date of ${inst.toISO()}`
765
+ );
766
+ }
767
+
768
+ return inst;
769
+ }
770
+
771
+ /**
772
+ * Create a DateTime from an ISO 8601 string
773
+ * @param {string} text - the ISO string
774
+ * @param {Object} opts - options to affect the creation
775
+ * @param {string|Zone} [opts.zone='local'] - use this zone if no offset is specified in the input string itself. Will also convert the time to this zone
776
+ * @param {boolean} [opts.setZone=false] - override the zone with a fixed-offset zone specified in the string itself, if it specifies one
777
+ * @param {string} [opts.locale='system's locale'] - a locale to set on the resulting DateTime instance
778
+ * @param {string} [opts.outputCalendar] - the output calendar to set on the resulting DateTime instance
779
+ * @param {string} [opts.numberingSystem] - the numbering system to set on the resulting DateTime instance
780
+ * @example DateTime.fromISO('2016-05-25T09:08:34.123')
781
+ * @example DateTime.fromISO('2016-05-25T09:08:34.123+06:00')
782
+ * @example DateTime.fromISO('2016-05-25T09:08:34.123+06:00', {setZone: true})
783
+ * @example DateTime.fromISO('2016-05-25T09:08:34.123', {zone: 'utc'})
784
+ * @example DateTime.fromISO('2016-W05-4')
785
+ * @return {DateTime}
786
+ */
787
+ static fromISO(text, opts = {}) {
788
+ const [vals, parsedZone] = parseISODate(text);
789
+ return parseDataToDateTime(vals, parsedZone, opts, "ISO 8601", text);
790
+ }
791
+
792
+ /**
793
+ * Create a DateTime from an RFC 2822 string
794
+ * @param {string} text - the RFC 2822 string
795
+ * @param {Object} opts - options to affect the creation
796
+ * @param {string|Zone} [opts.zone='local'] - convert the time to this zone. Since the offset is always specified in the string itself, this has no effect on the interpretation of string, merely the zone the resulting DateTime is expressed in.
797
+ * @param {boolean} [opts.setZone=false] - override the zone with a fixed-offset zone specified in the string itself, if it specifies one
798
+ * @param {string} [opts.locale='system's locale'] - a locale to set on the resulting DateTime instance
799
+ * @param {string} opts.outputCalendar - the output calendar to set on the resulting DateTime instance
800
+ * @param {string} opts.numberingSystem - the numbering system to set on the resulting DateTime instance
801
+ * @example DateTime.fromRFC2822('25 Nov 2016 13:23:12 GMT')
802
+ * @example DateTime.fromRFC2822('Fri, 25 Nov 2016 13:23:12 +0600')
803
+ * @example DateTime.fromRFC2822('25 Nov 2016 13:23 Z')
804
+ * @return {DateTime}
805
+ */
806
+ static fromRFC2822(text, opts = {}) {
807
+ const [vals, parsedZone] = parseRFC2822Date(text);
808
+ return parseDataToDateTime(vals, parsedZone, opts, "RFC 2822", text);
809
+ }
810
+
811
+ /**
812
+ * Create a DateTime from an HTTP header date
813
+ * @see https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3.1
814
+ * @param {string} text - the HTTP header date
815
+ * @param {Object} opts - options to affect the creation
816
+ * @param {string|Zone} [opts.zone='local'] - convert the time to this zone. Since HTTP dates are always in UTC, this has no effect on the interpretation of string, merely the zone the resulting DateTime is expressed in.
817
+ * @param {boolean} [opts.setZone=false] - override the zone with the fixed-offset zone specified in the string. For HTTP dates, this is always UTC, so this option is equivalent to setting the `zone` option to 'utc', but this option is included for consistency with similar methods.
818
+ * @param {string} [opts.locale='system's locale'] - a locale to set on the resulting DateTime instance
819
+ * @param {string} opts.outputCalendar - the output calendar to set on the resulting DateTime instance
820
+ * @param {string} opts.numberingSystem - the numbering system to set on the resulting DateTime instance
821
+ * @example DateTime.fromHTTP('Sun, 06 Nov 1994 08:49:37 GMT')
822
+ * @example DateTime.fromHTTP('Sunday, 06-Nov-94 08:49:37 GMT')
823
+ * @example DateTime.fromHTTP('Sun Nov 6 08:49:37 1994')
824
+ * @return {DateTime}
825
+ */
826
+ static fromHTTP(text, opts = {}) {
827
+ const [vals, parsedZone] = parseHTTPDate(text);
828
+ return parseDataToDateTime(vals, parsedZone, opts, "HTTP", opts);
829
+ }
830
+
831
+ /**
832
+ * Create a DateTime from an input string and format string.
833
+ * Defaults to en-US if no locale has been specified, regardless of the system's locale. For a table of tokens and their interpretations, see [here](https://moment.github.io/luxon/#/parsing?id=table-of-tokens).
834
+ * @param {string} text - the string to parse
835
+ * @param {string} fmt - the format the string is expected to be in (see the link below for the formats)
836
+ * @param {Object} opts - options to affect the creation
837
+ * @param {string|Zone} [opts.zone='local'] - use this zone if no offset is specified in the input string itself. Will also convert the DateTime to this zone
838
+ * @param {boolean} [opts.setZone=false] - override the zone with a zone specified in the string itself, if it specifies one
839
+ * @param {string} [opts.locale='en-US'] - a locale string to use when parsing. Will also set the DateTime to this locale
840
+ * @param {string} opts.numberingSystem - the numbering system to use when parsing. Will also set the resulting DateTime to this numbering system
841
+ * @param {string} opts.outputCalendar - the output calendar to set on the resulting DateTime instance
842
+ * @return {DateTime}
843
+ */
844
+ static fromFormat(text, fmt, opts = {}) {
845
+ if (isUndefined(text) || isUndefined(fmt)) {
846
+ throw new InvalidArgumentError("fromFormat requires an input string and a format");
847
+ }
848
+
849
+ const { locale = null, numberingSystem = null } = opts,
850
+ localeToUse = Locale.fromOpts({
851
+ locale,
852
+ numberingSystem,
853
+ defaultToEN: true,
854
+ }),
855
+ [vals, parsedZone, specificOffset, invalid] = parseFromTokens(localeToUse, text, fmt);
856
+ if (invalid) {
857
+ return DateTime.invalid(invalid);
858
+ } else {
859
+ return parseDataToDateTime(vals, parsedZone, opts, `format ${fmt}`, text, specificOffset);
860
+ }
861
+ }
862
+
863
+ /**
864
+ * @deprecated use fromFormat instead
865
+ */
866
+ static fromString(text, fmt, opts = {}) {
867
+ return DateTime.fromFormat(text, fmt, opts);
868
+ }
869
+
870
+ /**
871
+ * Create a DateTime from a SQL date, time, or datetime
872
+ * Defaults to en-US if no locale has been specified, regardless of the system's locale
873
+ * @param {string} text - the string to parse
874
+ * @param {Object} opts - options to affect the creation
875
+ * @param {string|Zone} [opts.zone='local'] - use this zone if no offset is specified in the input string itself. Will also convert the DateTime to this zone
876
+ * @param {boolean} [opts.setZone=false] - override the zone with a zone specified in the string itself, if it specifies one
877
+ * @param {string} [opts.locale='en-US'] - a locale string to use when parsing. Will also set the DateTime to this locale
878
+ * @param {string} opts.numberingSystem - the numbering system to use when parsing. Will also set the resulting DateTime to this numbering system
879
+ * @param {string} opts.outputCalendar - the output calendar to set on the resulting DateTime instance
880
+ * @example DateTime.fromSQL('2017-05-15')
881
+ * @example DateTime.fromSQL('2017-05-15 09:12:34')
882
+ * @example DateTime.fromSQL('2017-05-15 09:12:34.342')
883
+ * @example DateTime.fromSQL('2017-05-15 09:12:34.342+06:00')
884
+ * @example DateTime.fromSQL('2017-05-15 09:12:34.342 America/Los_Angeles')
885
+ * @example DateTime.fromSQL('2017-05-15 09:12:34.342 America/Los_Angeles', { setZone: true })
886
+ * @example DateTime.fromSQL('2017-05-15 09:12:34.342', { zone: 'America/Los_Angeles' })
887
+ * @example DateTime.fromSQL('09:12:34.342')
888
+ * @return {DateTime}
889
+ */
890
+ static fromSQL(text, opts = {}) {
891
+ const [vals, parsedZone] = parseSQL(text);
892
+ return parseDataToDateTime(vals, parsedZone, opts, "SQL", text);
893
+ }
894
+
895
+ /**
896
+ * Create an invalid DateTime.
897
+ * @param {DateTime} reason - simple string of why this DateTime is invalid. Should not contain parameters or anything else data-dependent
898
+ * @param {string} [explanation=null] - longer explanation, may include parameters and other useful debugging information
899
+ * @return {DateTime}
900
+ */
901
+ static invalid(reason, explanation = null) {
902
+ if (!reason) {
903
+ throw new InvalidArgumentError("need to specify a reason the DateTime is invalid");
904
+ }
905
+
906
+ const invalid = reason instanceof Invalid ? reason : new Invalid(reason, explanation);
907
+
908
+ if (Settings.throwOnInvalid) {
909
+ throw new InvalidDateTimeError(invalid);
910
+ } else {
911
+ return new DateTime({ invalid });
912
+ }
913
+ }
914
+
915
+ /**
916
+ * Check if an object is an instance of DateTime. Works across context boundaries
917
+ * @param {object} o
918
+ * @return {boolean}
919
+ */
920
+ static isDateTime(o) {
921
+ return (o && o.isLuxonDateTime) || false;
922
+ }
923
+
924
+ /**
925
+ * Produce the format string for a set of options
926
+ * @param formatOpts
927
+ * @param localeOpts
928
+ * @returns {string}
929
+ */
930
+ static parseFormatForOpts(formatOpts, localeOpts = {}) {
931
+ const tokenList = formatOptsToTokens(formatOpts, Locale.fromObject(localeOpts));
932
+ return !tokenList ? null : tokenList.map((t) => (t ? t.val : null)).join("");
933
+ }
934
+
935
+ /**
936
+ * Produce the the fully expanded format token for the locale
937
+ * Does NOT quote characters, so quoted tokens will not round trip correctly
938
+ * @param fmt
939
+ * @param localeOpts
940
+ * @returns {string}
941
+ */
942
+ static expandFormat(fmt, localeOpts = {}) {
943
+ const expanded = expandMacroTokens(Formatter.parseFormat(fmt), Locale.fromObject(localeOpts));
944
+ return expanded.map((t) => t.val).join("");
945
+ }
946
+
947
+ // INFO
948
+
949
+ /**
950
+ * Get the value of unit.
951
+ * @param {string} unit - a unit such as 'minute' or 'day'
952
+ * @example DateTime.local(2017, 7, 4).get('month'); //=> 7
953
+ * @example DateTime.local(2017, 7, 4).get('day'); //=> 4
954
+ * @return {number}
955
+ */
956
+ get(unit) {
957
+ return this[unit];
958
+ }
959
+
960
+ /**
961
+ * Returns whether the DateTime is valid. Invalid DateTimes occur when:
962
+ * * The DateTime was created from invalid calendar information, such as the 13th month or February 30
963
+ * * The DateTime was created by an operation on another invalid date
964
+ * @type {boolean}
965
+ */
966
+ get isValid() {
967
+ return this.invalid === null;
968
+ }
969
+
970
+ /**
971
+ * Returns an error code if this DateTime is invalid, or null if the DateTime is valid
972
+ * @type {string}
973
+ */
974
+ get invalidReason() {
975
+ return this.invalid ? this.invalid.reason : null;
976
+ }
977
+
978
+ /**
979
+ * Returns an explanation of why this DateTime became invalid, or null if the DateTime is valid
980
+ * @type {string}
981
+ */
982
+ get invalidExplanation() {
983
+ return this.invalid ? this.invalid.explanation : null;
984
+ }
985
+
986
+ /**
987
+ * Get the locale of a DateTime, such 'en-GB'. The locale is used when formatting the DateTime
988
+ *
989
+ * @type {string}
990
+ */
991
+ get locale() {
992
+ return this.isValid ? this.loc.locale : null;
993
+ }
994
+
995
+ /**
996
+ * Get the numbering system of a DateTime, such 'beng'. The numbering system is used when formatting the DateTime
997
+ *
998
+ * @type {string}
999
+ */
1000
+ get numberingSystem() {
1001
+ return this.isValid ? this.loc.numberingSystem : null;
1002
+ }
1003
+
1004
+ /**
1005
+ * Get the output calendar of a DateTime, such 'islamic'. The output calendar is used when formatting the DateTime
1006
+ *
1007
+ * @type {string}
1008
+ */
1009
+ get outputCalendar() {
1010
+ return this.isValid ? this.loc.outputCalendar : null;
1011
+ }
1012
+
1013
+ /**
1014
+ * Get the time zone associated with this DateTime.
1015
+ * @type {Zone}
1016
+ */
1017
+ get zone() {
1018
+ return this._zone;
1019
+ }
1020
+
1021
+ /**
1022
+ * Get the name of the time zone.
1023
+ * @type {string}
1024
+ */
1025
+ get zoneName() {
1026
+ return this.isValid ? this.zone.name : null;
1027
+ }
1028
+
1029
+ /**
1030
+ * Get the year
1031
+ * @example DateTime.local(2017, 5, 25).year //=> 2017
1032
+ * @type {number}
1033
+ */
1034
+ get year() {
1035
+ return this.isValid ? this.c.year : NaN;
1036
+ }
1037
+
1038
+ /**
1039
+ * Get the quarter
1040
+ * @example DateTime.local(2017, 5, 25).quarter //=> 2
1041
+ * @type {number}
1042
+ */
1043
+ get quarter() {
1044
+ return this.isValid ? Math.ceil(this.c.month / 3) : NaN;
1045
+ }
1046
+
1047
+ /**
1048
+ * Get the month (1-12).
1049
+ * @example DateTime.local(2017, 5, 25).month //=> 5
1050
+ * @type {number}
1051
+ */
1052
+ get month() {
1053
+ return this.isValid ? this.c.month : NaN;
1054
+ }
1055
+
1056
+ /**
1057
+ * Get the day of the month (1-30ish).
1058
+ * @example DateTime.local(2017, 5, 25).day //=> 25
1059
+ * @type {number}
1060
+ */
1061
+ get day() {
1062
+ return this.isValid ? this.c.day : NaN;
1063
+ }
1064
+
1065
+ /**
1066
+ * Get the hour of the day (0-23).
1067
+ * @example DateTime.local(2017, 5, 25, 9).hour //=> 9
1068
+ * @type {number}
1069
+ */
1070
+ get hour() {
1071
+ return this.isValid ? this.c.hour : NaN;
1072
+ }
1073
+
1074
+ /**
1075
+ * Get the minute of the hour (0-59).
1076
+ * @example DateTime.local(2017, 5, 25, 9, 30).minute //=> 30
1077
+ * @type {number}
1078
+ */
1079
+ get minute() {
1080
+ return this.isValid ? this.c.minute : NaN;
1081
+ }
1082
+
1083
+ /**
1084
+ * Get the second of the minute (0-59).
1085
+ * @example DateTime.local(2017, 5, 25, 9, 30, 52).second //=> 52
1086
+ * @type {number}
1087
+ */
1088
+ get second() {
1089
+ return this.isValid ? this.c.second : NaN;
1090
+ }
1091
+
1092
+ /**
1093
+ * Get the millisecond of the second (0-999).
1094
+ * @example DateTime.local(2017, 5, 25, 9, 30, 52, 654).millisecond //=> 654
1095
+ * @type {number}
1096
+ */
1097
+ get millisecond() {
1098
+ return this.isValid ? this.c.millisecond : NaN;
1099
+ }
1100
+
1101
+ /**
1102
+ * Get the week year
1103
+ * @see https://en.wikipedia.org/wiki/ISO_week_date
1104
+ * @example DateTime.local(2014, 12, 31).weekYear //=> 2015
1105
+ * @type {number}
1106
+ */
1107
+ get weekYear() {
1108
+ return this.isValid ? possiblyCachedWeekData(this).weekYear : NaN;
1109
+ }
1110
+
1111
+ /**
1112
+ * Get the week number of the week year (1-52ish).
1113
+ * @see https://en.wikipedia.org/wiki/ISO_week_date
1114
+ * @example DateTime.local(2017, 5, 25).weekNumber //=> 21
1115
+ * @type {number}
1116
+ */
1117
+ get weekNumber() {
1118
+ return this.isValid ? possiblyCachedWeekData(this).weekNumber : NaN;
1119
+ }
1120
+
1121
+ /**
1122
+ * Get the day of the week.
1123
+ * 1 is Monday and 7 is Sunday
1124
+ * @see https://en.wikipedia.org/wiki/ISO_week_date
1125
+ * @example DateTime.local(2014, 11, 31).weekday //=> 4
1126
+ * @type {number}
1127
+ */
1128
+ get weekday() {
1129
+ return this.isValid ? possiblyCachedWeekData(this).weekday : NaN;
1130
+ }
1131
+
1132
+ /**
1133
+ * Get the ordinal (meaning the day of the year)
1134
+ * @example DateTime.local(2017, 5, 25).ordinal //=> 145
1135
+ * @type {number|DateTime}
1136
+ */
1137
+ get ordinal() {
1138
+ return this.isValid ? gregorianToOrdinal(this.c).ordinal : NaN;
1139
+ }
1140
+
1141
+ /**
1142
+ * Get the human readable short month name, such as 'Oct'.
1143
+ * Defaults to the system's locale if no locale has been specified
1144
+ * @example DateTime.local(2017, 10, 30).monthShort //=> Oct
1145
+ * @type {string}
1146
+ */
1147
+ get monthShort() {
1148
+ return this.isValid ? Info.months("short", { locObj: this.loc })[this.month - 1] : null;
1149
+ }
1150
+
1151
+ /**
1152
+ * Get the human readable long month name, such as 'October'.
1153
+ * Defaults to the system's locale if no locale has been specified
1154
+ * @example DateTime.local(2017, 10, 30).monthLong //=> October
1155
+ * @type {string}
1156
+ */
1157
+ get monthLong() {
1158
+ return this.isValid ? Info.months("long", { locObj: this.loc })[this.month - 1] : null;
1159
+ }
1160
+
1161
+ /**
1162
+ * Get the human readable short weekday, such as 'Mon'.
1163
+ * Defaults to the system's locale if no locale has been specified
1164
+ * @example DateTime.local(2017, 10, 30).weekdayShort //=> Mon
1165
+ * @type {string}
1166
+ */
1167
+ get weekdayShort() {
1168
+ return this.isValid ? Info.weekdays("short", { locObj: this.loc })[this.weekday - 1] : null;
1169
+ }
1170
+
1171
+ /**
1172
+ * Get the human readable long weekday, such as 'Monday'.
1173
+ * Defaults to the system's locale if no locale has been specified
1174
+ * @example DateTime.local(2017, 10, 30).weekdayLong //=> Monday
1175
+ * @type {string}
1176
+ */
1177
+ get weekdayLong() {
1178
+ return this.isValid ? Info.weekdays("long", { locObj: this.loc })[this.weekday - 1] : null;
1179
+ }
1180
+
1181
+ /**
1182
+ * Get the UTC offset of this DateTime in minutes
1183
+ * @example DateTime.now().offset //=> -240
1184
+ * @example DateTime.utc().offset //=> 0
1185
+ * @type {number}
1186
+ */
1187
+ get offset() {
1188
+ return this.isValid ? +this.o : NaN;
1189
+ }
1190
+
1191
+ /**
1192
+ * Get the short human name for the zone's current offset, for example "EST" or "EDT".
1193
+ * Defaults to the system's locale if no locale has been specified
1194
+ * @type {string}
1195
+ */
1196
+ get offsetNameShort() {
1197
+ if (this.isValid) {
1198
+ return this.zone.offsetName(this.ts, {
1199
+ format: "short",
1200
+ locale: this.locale,
1201
+ });
1202
+ } else {
1203
+ return null;
1204
+ }
1205
+ }
1206
+
1207
+ /**
1208
+ * Get the long human name for the zone's current offset, for example "Eastern Standard Time" or "Eastern Daylight Time".
1209
+ * Defaults to the system's locale if no locale has been specified
1210
+ * @type {string}
1211
+ */
1212
+ get offsetNameLong() {
1213
+ if (this.isValid) {
1214
+ return this.zone.offsetName(this.ts, {
1215
+ format: "long",
1216
+ locale: this.locale,
1217
+ });
1218
+ } else {
1219
+ return null;
1220
+ }
1221
+ }
1222
+
1223
+ /**
1224
+ * Get whether this zone's offset ever changes, as in a DST.
1225
+ * @type {boolean}
1226
+ */
1227
+ get isOffsetFixed() {
1228
+ return this.isValid ? this.zone.isUniversal : null;
1229
+ }
1230
+
1231
+ /**
1232
+ * Get whether the DateTime is in a DST.
1233
+ * @type {boolean}
1234
+ */
1235
+ get isInDST() {
1236
+ if (this.isOffsetFixed) {
1237
+ return false;
1238
+ } else {
1239
+ return (
1240
+ this.offset > this.set({ month: 1, day: 1 }).offset ||
1241
+ this.offset > this.set({ month: 5 }).offset
1242
+ );
1243
+ }
1244
+ }
1245
+
1246
+ /**
1247
+ * Returns true if this DateTime is in a leap year, false otherwise
1248
+ * @example DateTime.local(2016).isInLeapYear //=> true
1249
+ * @example DateTime.local(2013).isInLeapYear //=> false
1250
+ * @type {boolean}
1251
+ */
1252
+ get isInLeapYear() {
1253
+ return isLeapYear(this.year);
1254
+ }
1255
+
1256
+ /**
1257
+ * Returns the number of days in this DateTime's month
1258
+ * @example DateTime.local(2016, 2).daysInMonth //=> 29
1259
+ * @example DateTime.local(2016, 3).daysInMonth //=> 31
1260
+ * @type {number}
1261
+ */
1262
+ get daysInMonth() {
1263
+ return daysInMonth(this.year, this.month);
1264
+ }
1265
+
1266
+ /**
1267
+ * Returns the number of days in this DateTime's year
1268
+ * @example DateTime.local(2016).daysInYear //=> 366
1269
+ * @example DateTime.local(2013).daysInYear //=> 365
1270
+ * @type {number}
1271
+ */
1272
+ get daysInYear() {
1273
+ return this.isValid ? daysInYear(this.year) : NaN;
1274
+ }
1275
+
1276
+ /**
1277
+ * Returns the number of weeks in this DateTime's year
1278
+ * @see https://en.wikipedia.org/wiki/ISO_week_date
1279
+ * @example DateTime.local(2004).weeksInWeekYear //=> 53
1280
+ * @example DateTime.local(2013).weeksInWeekYear //=> 52
1281
+ * @type {number}
1282
+ */
1283
+ get weeksInWeekYear() {
1284
+ return this.isValid ? weeksInWeekYear(this.weekYear) : NaN;
1285
+ }
1286
+
1287
+ /**
1288
+ * Returns the resolved Intl options for this DateTime.
1289
+ * This is useful in understanding the behavior of formatting methods
1290
+ * @param {Object} opts - the same options as toLocaleString
1291
+ * @return {Object}
1292
+ */
1293
+ resolvedLocaleOptions(opts = {}) {
1294
+ const { locale, numberingSystem, calendar } = Formatter.create(
1295
+ this.loc.clone(opts),
1296
+ opts
1297
+ ).resolvedOptions(this);
1298
+ return { locale, numberingSystem, outputCalendar: calendar };
1299
+ }
1300
+
1301
+ // TRANSFORM
1302
+
1303
+ /**
1304
+ * "Set" the DateTime's zone to UTC. Returns a newly-constructed DateTime.
1305
+ *
1306
+ * Equivalent to {@link DateTime#setZone}('utc')
1307
+ * @param {number} [offset=0] - optionally, an offset from UTC in minutes
1308
+ * @param {Object} [opts={}] - options to pass to `setZone()`
1309
+ * @return {DateTime}
1310
+ */
1311
+ toUTC(offset = 0, opts = {}) {
1312
+ return this.setZone(FixedOffsetZone.instance(offset), opts);
1313
+ }
1314
+
1315
+ /**
1316
+ * "Set" the DateTime's zone to the host's local zone. Returns a newly-constructed DateTime.
1317
+ *
1318
+ * Equivalent to `setZone('local')`
1319
+ * @return {DateTime}
1320
+ */
1321
+ toLocal() {
1322
+ return this.setZone(Settings.defaultZone);
1323
+ }
1324
+
1325
+ /**
1326
+ * "Set" the DateTime's zone to specified zone. Returns a newly-constructed DateTime.
1327
+ *
1328
+ * By default, the setter keeps the underlying time the same (as in, the same timestamp), but the new instance will report different local times and consider DSTs when making computations, as with {@link DateTime#plus}. You may wish to use {@link DateTime#toLocal} and {@link DateTime#toUTC} which provide simple convenience wrappers for commonly used zones.
1329
+ * @param {string|Zone} [zone='local'] - a zone identifier. As a string, that can be any IANA zone supported by the host environment, or a fixed-offset name of the form 'UTC+3', or the strings 'local' or 'utc'. You may also supply an instance of a {@link DateTime#Zone} class.
1330
+ * @param {Object} opts - options
1331
+ * @param {boolean} [opts.keepLocalTime=false] - If true, adjust the underlying time so that the local time stays the same, but in the target zone. You should rarely need this.
1332
+ * @return {DateTime}
1333
+ */
1334
+ setZone(zone, { keepLocalTime = false, keepCalendarTime = false } = {}) {
1335
+ zone = normalizeZone(zone, Settings.defaultZone);
1336
+ if (zone.equals(this.zone)) {
1337
+ return this;
1338
+ } else if (!zone.isValid) {
1339
+ return DateTime.invalid(unsupportedZone(zone));
1340
+ } else {
1341
+ let newTS = this.ts;
1342
+ if (keepLocalTime || keepCalendarTime) {
1343
+ const offsetGuess = zone.offset(this.ts);
1344
+ const asObj = this.toObject();
1345
+ [newTS] = objToTS(asObj, offsetGuess, zone);
1346
+ }
1347
+ return clone(this, { ts: newTS, zone });
1348
+ }
1349
+ }
1350
+
1351
+ /**
1352
+ * "Set" the locale, numberingSystem, or outputCalendar. Returns a newly-constructed DateTime.
1353
+ * @param {Object} properties - the properties to set
1354
+ * @example DateTime.local(2017, 5, 25).reconfigure({ locale: 'en-GB' })
1355
+ * @return {DateTime}
1356
+ */
1357
+ reconfigure({ locale, numberingSystem, outputCalendar } = {}) {
1358
+ const loc = this.loc.clone({ locale, numberingSystem, outputCalendar });
1359
+ return clone(this, { loc });
1360
+ }
1361
+
1362
+ /**
1363
+ * "Set" the locale. Returns a newly-constructed DateTime.
1364
+ * Just a convenient alias for reconfigure({ locale })
1365
+ * @example DateTime.local(2017, 5, 25).setLocale('en-GB')
1366
+ * @return {DateTime}
1367
+ */
1368
+ setLocale(locale) {
1369
+ return this.reconfigure({ locale });
1370
+ }
1371
+
1372
+ /**
1373
+ * "Set" the values of specified units. Returns a newly-constructed DateTime.
1374
+ * You can only set units with this method; for "setting" metadata, see {@link DateTime#reconfigure} and {@link DateTime#setZone}.
1375
+ * @param {Object} values - a mapping of units to numbers
1376
+ * @example dt.set({ year: 2017 })
1377
+ * @example dt.set({ hour: 8, minute: 30 })
1378
+ * @example dt.set({ weekday: 5 })
1379
+ * @example dt.set({ year: 2005, ordinal: 234 })
1380
+ * @return {DateTime}
1381
+ */
1382
+ set(values) {
1383
+ if (!this.isValid) return this;
1384
+
1385
+ const normalized = normalizeObject(values, normalizeUnit),
1386
+ settingWeekStuff =
1387
+ !isUndefined(normalized.weekYear) ||
1388
+ !isUndefined(normalized.weekNumber) ||
1389
+ !isUndefined(normalized.weekday),
1390
+ containsOrdinal = !isUndefined(normalized.ordinal),
1391
+ containsGregorYear = !isUndefined(normalized.year),
1392
+ containsGregorMD = !isUndefined(normalized.month) || !isUndefined(normalized.day),
1393
+ containsGregor = containsGregorYear || containsGregorMD,
1394
+ definiteWeekDef = normalized.weekYear || normalized.weekNumber;
1395
+
1396
+ if ((containsGregor || containsOrdinal) && definiteWeekDef) {
1397
+ throw new ConflictingSpecificationError(
1398
+ "Can't mix weekYear/weekNumber units with year/month/day or ordinals"
1399
+ );
1400
+ }
1401
+
1402
+ if (containsGregorMD && containsOrdinal) {
1403
+ throw new ConflictingSpecificationError("Can't mix ordinal dates with month/day");
1404
+ }
1405
+
1406
+ let mixed;
1407
+ if (settingWeekStuff) {
1408
+ mixed = weekToGregorian({ ...gregorianToWeek(this.c), ...normalized });
1409
+ } else if (!isUndefined(normalized.ordinal)) {
1410
+ mixed = ordinalToGregorian({ ...gregorianToOrdinal(this.c), ...normalized });
1411
+ } else {
1412
+ mixed = { ...this.toObject(), ...normalized };
1413
+
1414
+ // if we didn't set the day but we ended up on an overflow date,
1415
+ // use the last day of the right month
1416
+ if (isUndefined(normalized.day)) {
1417
+ mixed.day = Math.min(daysInMonth(mixed.year, mixed.month), mixed.day);
1418
+ }
1419
+ }
1420
+
1421
+ const [ts, o] = objToTS(mixed, this.o, this.zone);
1422
+ return clone(this, { ts, o });
1423
+ }
1424
+
1425
+ /**
1426
+ * Add a period of time to this DateTime and return the resulting DateTime
1427
+ *
1428
+ * Adding hours, minutes, seconds, or milliseconds increases the timestamp by the right number of milliseconds. Adding days, months, or years shifts the calendar, accounting for DSTs and leap years along the way. Thus, `dt.plus({ hours: 24 })` may result in a different time than `dt.plus({ days: 1 })` if there's a DST shift in between.
1429
+ * @param {Duration|Object|number} duration - The amount to add. Either a Luxon Duration, a number of milliseconds, the object argument to Duration.fromObject()
1430
+ * @example DateTime.now().plus(123) //~> in 123 milliseconds
1431
+ * @example DateTime.now().plus({ minutes: 15 }) //~> in 15 minutes
1432
+ * @example DateTime.now().plus({ days: 1 }) //~> this time tomorrow
1433
+ * @example DateTime.now().plus({ days: -1 }) //~> this time yesterday
1434
+ * @example DateTime.now().plus({ hours: 3, minutes: 13 }) //~> in 3 hr, 13 min
1435
+ * @example DateTime.now().plus(Duration.fromObject({ hours: 3, minutes: 13 })) //~> in 3 hr, 13 min
1436
+ * @return {DateTime}
1437
+ */
1438
+ plus(duration) {
1439
+ if (!this.isValid) return this;
1440
+ const dur = Duration.fromDurationLike(duration);
1441
+ return clone(this, adjustTime(this, dur));
1442
+ }
1443
+
1444
+ /**
1445
+ * Subtract a period of time to this DateTime and return the resulting DateTime
1446
+ * See {@link DateTime#plus}
1447
+ * @param {Duration|Object|number} duration - The amount to subtract. Either a Luxon Duration, a number of milliseconds, the object argument to Duration.fromObject()
1448
+ @return {DateTime}
1449
+ */
1450
+ minus(duration) {
1451
+ if (!this.isValid) return this;
1452
+ const dur = Duration.fromDurationLike(duration).negate();
1453
+ return clone(this, adjustTime(this, dur));
1454
+ }
1455
+
1456
+ /**
1457
+ * "Set" this DateTime to the beginning of a unit of time.
1458
+ * @param {string} unit - The unit to go to the beginning of. Can be 'year', 'quarter', 'month', 'week', 'day', 'hour', 'minute', 'second', or 'millisecond'.
1459
+ * @example DateTime.local(2014, 3, 3).startOf('month').toISODate(); //=> '2014-03-01'
1460
+ * @example DateTime.local(2014, 3, 3).startOf('year').toISODate(); //=> '2014-01-01'
1461
+ * @example DateTime.local(2014, 3, 3).startOf('week').toISODate(); //=> '2014-03-03', weeks always start on Mondays
1462
+ * @example DateTime.local(2014, 3, 3, 5, 30).startOf('day').toISOTime(); //=> '00:00.000-05:00'
1463
+ * @example DateTime.local(2014, 3, 3, 5, 30).startOf('hour').toISOTime(); //=> '05:00:00.000-05:00'
1464
+ * @return {DateTime}
1465
+ */
1466
+ startOf(unit) {
1467
+ if (!this.isValid) return this;
1468
+ const o = {},
1469
+ normalizedUnit = Duration.normalizeUnit(unit);
1470
+ switch (normalizedUnit) {
1471
+ case "years":
1472
+ o.month = 1;
1473
+ // falls through
1474
+ case "quarters":
1475
+ case "months":
1476
+ o.day = 1;
1477
+ // falls through
1478
+ case "weeks":
1479
+ case "days":
1480
+ o.hour = 0;
1481
+ // falls through
1482
+ case "hours":
1483
+ o.minute = 0;
1484
+ // falls through
1485
+ case "minutes":
1486
+ o.second = 0;
1487
+ // falls through
1488
+ case "seconds":
1489
+ o.millisecond = 0;
1490
+ break;
1491
+ case "milliseconds":
1492
+ break;
1493
+ // no default, invalid units throw in normalizeUnit()
1494
+ }
1495
+
1496
+ if (normalizedUnit === "weeks") {
1497
+ o.weekday = 1;
1498
+ }
1499
+
1500
+ if (normalizedUnit === "quarters") {
1501
+ const q = Math.ceil(this.month / 3);
1502
+ o.month = (q - 1) * 3 + 1;
1503
+ }
1504
+
1505
+ return this.set(o);
1506
+ }
1507
+
1508
+ /**
1509
+ * "Set" this DateTime to the end (meaning the last millisecond) of a unit of time
1510
+ * @param {string} unit - The unit to go to the end of. Can be 'year', 'quarter', 'month', 'week', 'day', 'hour', 'minute', 'second', or 'millisecond'.
1511
+ * @example DateTime.local(2014, 3, 3).endOf('month').toISO(); //=> '2014-03-31T23:59:59.999-05:00'
1512
+ * @example DateTime.local(2014, 3, 3).endOf('year').toISO(); //=> '2014-12-31T23:59:59.999-05:00'
1513
+ * @example DateTime.local(2014, 3, 3).endOf('week').toISO(); // => '2014-03-09T23:59:59.999-05:00', weeks start on Mondays
1514
+ * @example DateTime.local(2014, 3, 3, 5, 30).endOf('day').toISO(); //=> '2014-03-03T23:59:59.999-05:00'
1515
+ * @example DateTime.local(2014, 3, 3, 5, 30).endOf('hour').toISO(); //=> '2014-03-03T05:59:59.999-05:00'
1516
+ * @return {DateTime}
1517
+ */
1518
+ endOf(unit) {
1519
+ return this.isValid
1520
+ ? this.plus({ [unit]: 1 })
1521
+ .startOf(unit)
1522
+ .minus(1)
1523
+ : this;
1524
+ }
1525
+
1526
+ // OUTPUT
1527
+
1528
+ /**
1529
+ * Returns a string representation of this DateTime formatted according to the specified format string.
1530
+ * **You may not want this.** See {@link DateTime#toLocaleString} for a more flexible formatting tool. For a table of tokens and their interpretations, see [here](https://moment.github.io/luxon/#/formatting?id=table-of-tokens).
1531
+ * Defaults to en-US if no locale has been specified, regardless of the system's locale.
1532
+ * @param {string} fmt - the format string
1533
+ * @param {Object} opts - opts to override the configuration options on this DateTime
1534
+ * @example DateTime.now().toFormat('yyyy LLL dd') //=> '2017 Apr 22'
1535
+ * @example DateTime.now().setLocale('fr').toFormat('yyyy LLL dd') //=> '2017 avr. 22'
1536
+ * @example DateTime.now().toFormat('yyyy LLL dd', { locale: "fr" }) //=> '2017 avr. 22'
1537
+ * @example DateTime.now().toFormat("HH 'hours and' mm 'minutes'") //=> '20 hours and 55 minutes'
1538
+ * @return {string}
1539
+ */
1540
+ toFormat(fmt, opts = {}) {
1541
+ return this.isValid
1542
+ ? Formatter.create(this.loc.redefaultToEN(opts)).formatDateTimeFromString(this, fmt)
1543
+ : INVALID;
1544
+ }
1545
+
1546
+ /**
1547
+ * Returns a localized string representing this date. Accepts the same options as the Intl.DateTimeFormat constructor and any presets defined by Luxon, such as `DateTime.DATE_FULL` or `DateTime.TIME_SIMPLE`.
1548
+ * The exact behavior of this method is browser-specific, but in general it will return an appropriate representation
1549
+ * of the DateTime in the assigned locale.
1550
+ * Defaults to the system's locale if no locale has been specified
1551
+ * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat
1552
+ * @param formatOpts {Object} - Intl.DateTimeFormat constructor options and configuration options
1553
+ * @param {Object} opts - opts to override the configuration options on this DateTime
1554
+ * @example DateTime.now().toLocaleString(); //=> 4/20/2017
1555
+ * @example DateTime.now().setLocale('en-gb').toLocaleString(); //=> '20/04/2017'
1556
+ * @example DateTime.now().toLocaleString(DateTime.DATE_FULL); //=> 'April 20, 2017'
1557
+ * @example DateTime.now().toLocaleString(DateTime.DATE_FULL, { locale: 'fr' }); //=> '28 août 2022'
1558
+ * @example DateTime.now().toLocaleString(DateTime.TIME_SIMPLE); //=> '11:32 AM'
1559
+ * @example DateTime.now().toLocaleString(DateTime.DATETIME_SHORT); //=> '4/20/2017, 11:32 AM'
1560
+ * @example DateTime.now().toLocaleString({ weekday: 'long', month: 'long', day: '2-digit' }); //=> 'Thursday, April 20'
1561
+ * @example DateTime.now().toLocaleString({ weekday: 'short', month: 'short', day: '2-digit', hour: '2-digit', minute: '2-digit' }); //=> 'Thu, Apr 20, 11:27 AM'
1562
+ * @example DateTime.now().toLocaleString({ hour: '2-digit', minute: '2-digit', hourCycle: 'h23' }); //=> '11:32'
1563
+ * @return {string}
1564
+ */
1565
+ toLocaleString(formatOpts = Formats.DATE_SHORT, opts = {}) {
1566
+ return this.isValid
1567
+ ? Formatter.create(this.loc.clone(opts), formatOpts).formatDateTime(this)
1568
+ : INVALID;
1569
+ }
1570
+
1571
+ /**
1572
+ * Returns an array of format "parts", meaning individual tokens along with metadata. This is allows callers to post-process individual sections of the formatted output.
1573
+ * Defaults to the system's locale if no locale has been specified
1574
+ * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat/formatToParts
1575
+ * @param opts {Object} - Intl.DateTimeFormat constructor options, same as `toLocaleString`.
1576
+ * @example DateTime.now().toLocaleParts(); //=> [
1577
+ * //=> { type: 'day', value: '25' },
1578
+ * //=> { type: 'literal', value: '/' },
1579
+ * //=> { type: 'month', value: '05' },
1580
+ * //=> { type: 'literal', value: '/' },
1581
+ * //=> { type: 'year', value: '1982' }
1582
+ * //=> ]
1583
+ */
1584
+ toLocaleParts(opts = {}) {
1585
+ return this.isValid
1586
+ ? Formatter.create(this.loc.clone(opts), opts).formatDateTimeParts(this)
1587
+ : [];
1588
+ }
1589
+
1590
+ /**
1591
+ * Returns an ISO 8601-compliant string representation of this DateTime
1592
+ * @param {Object} opts - options
1593
+ * @param {boolean} [opts.suppressMilliseconds=false] - exclude milliseconds from the format if they're 0
1594
+ * @param {boolean} [opts.suppressSeconds=false] - exclude seconds from the format if they're 0
1595
+ * @param {boolean} [opts.includeOffset=true] - include the offset, such as 'Z' or '-04:00'
1596
+ * @param {boolean} [opts.extendedZone=false] - add the time zone format extension
1597
+ * @param {string} [opts.format='extended'] - choose between the basic and extended format
1598
+ * @example DateTime.utc(1983, 5, 25).toISO() //=> '1982-05-25T00:00:00.000Z'
1599
+ * @example DateTime.now().toISO() //=> '2017-04-22T20:47:05.335-04:00'
1600
+ * @example DateTime.now().toISO({ includeOffset: false }) //=> '2017-04-22T20:47:05.335'
1601
+ * @example DateTime.now().toISO({ format: 'basic' }) //=> '20170422T204705.335-0400'
1602
+ * @return {string}
1603
+ */
1604
+ toISO({
1605
+ format = "extended",
1606
+ suppressSeconds = false,
1607
+ suppressMilliseconds = false,
1608
+ includeOffset = true,
1609
+ extendedZone = false,
1610
+ } = {}) {
1611
+ if (!this.isValid) {
1612
+ return null;
1613
+ }
1614
+
1615
+ const ext = format === "extended";
1616
+
1617
+ let c = toISODate(this, ext);
1618
+ c += "T";
1619
+ c += toISOTime(this, ext, suppressSeconds, suppressMilliseconds, includeOffset, extendedZone);
1620
+ return c;
1621
+ }
1622
+
1623
+ /**
1624
+ * Returns an ISO 8601-compliant string representation of this DateTime's date component
1625
+ * @param {Object} opts - options
1626
+ * @param {string} [opts.format='extended'] - choose between the basic and extended format
1627
+ * @example DateTime.utc(1982, 5, 25).toISODate() //=> '1982-05-25'
1628
+ * @example DateTime.utc(1982, 5, 25).toISODate({ format: 'basic' }) //=> '19820525'
1629
+ * @return {string}
1630
+ */
1631
+ toISODate({ format = "extended" } = {}) {
1632
+ if (!this.isValid) {
1633
+ return null;
1634
+ }
1635
+
1636
+ return toISODate(this, format === "extended");
1637
+ }
1638
+
1639
+ /**
1640
+ * Returns an ISO 8601-compliant string representation of this DateTime's week date
1641
+ * @example DateTime.utc(1982, 5, 25).toISOWeekDate() //=> '1982-W21-2'
1642
+ * @return {string}
1643
+ */
1644
+ toISOWeekDate() {
1645
+ return toTechFormat(this, "kkkk-'W'WW-c");
1646
+ }
1647
+
1648
+ /**
1649
+ * Returns an ISO 8601-compliant string representation of this DateTime's time component
1650
+ * @param {Object} opts - options
1651
+ * @param {boolean} [opts.suppressMilliseconds=false] - exclude milliseconds from the format if they're 0
1652
+ * @param {boolean} [opts.suppressSeconds=false] - exclude seconds from the format if they're 0
1653
+ * @param {boolean} [opts.includeOffset=true] - include the offset, such as 'Z' or '-04:00'
1654
+ * @param {boolean} [opts.extendedZone=true] - add the time zone format extension
1655
+ * @param {boolean} [opts.includePrefix=false] - include the `T` prefix
1656
+ * @param {string} [opts.format='extended'] - choose between the basic and extended format
1657
+ * @example DateTime.utc().set({ hour: 7, minute: 34 }).toISOTime() //=> '07:34:19.361Z'
1658
+ * @example DateTime.utc().set({ hour: 7, minute: 34, seconds: 0, milliseconds: 0 }).toISOTime({ suppressSeconds: true }) //=> '07:34Z'
1659
+ * @example DateTime.utc().set({ hour: 7, minute: 34 }).toISOTime({ format: 'basic' }) //=> '073419.361Z'
1660
+ * @example DateTime.utc().set({ hour: 7, minute: 34 }).toISOTime({ includePrefix: true }) //=> 'T07:34:19.361Z'
1661
+ * @return {string}
1662
+ */
1663
+ toISOTime({
1664
+ suppressMilliseconds = false,
1665
+ suppressSeconds = false,
1666
+ includeOffset = true,
1667
+ includePrefix = false,
1668
+ extendedZone = false,
1669
+ format = "extended",
1670
+ } = {}) {
1671
+ if (!this.isValid) {
1672
+ return null;
1673
+ }
1674
+
1675
+ let c = includePrefix ? "T" : "";
1676
+ return (
1677
+ c +
1678
+ toISOTime(
1679
+ this,
1680
+ format === "extended",
1681
+ suppressSeconds,
1682
+ suppressMilliseconds,
1683
+ includeOffset,
1684
+ extendedZone
1685
+ )
1686
+ );
1687
+ }
1688
+
1689
+ /**
1690
+ * Returns an RFC 2822-compatible string representation of this DateTime
1691
+ * @example DateTime.utc(2014, 7, 13).toRFC2822() //=> 'Sun, 13 Jul 2014 00:00:00 +0000'
1692
+ * @example DateTime.local(2014, 7, 13).toRFC2822() //=> 'Sun, 13 Jul 2014 00:00:00 -0400'
1693
+ * @return {string}
1694
+ */
1695
+ toRFC2822() {
1696
+ return toTechFormat(this, "EEE, dd LLL yyyy HH:mm:ss ZZZ", false);
1697
+ }
1698
+
1699
+ /**
1700
+ * Returns a string representation of this DateTime appropriate for use in HTTP headers. The output is always expressed in GMT.
1701
+ * Specifically, the string conforms to RFC 1123.
1702
+ * @see https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3.1
1703
+ * @example DateTime.utc(2014, 7, 13).toHTTP() //=> 'Sun, 13 Jul 2014 00:00:00 GMT'
1704
+ * @example DateTime.utc(2014, 7, 13, 19).toHTTP() //=> 'Sun, 13 Jul 2014 19:00:00 GMT'
1705
+ * @return {string}
1706
+ */
1707
+ toHTTP() {
1708
+ return toTechFormat(this.toUTC(), "EEE, dd LLL yyyy HH:mm:ss 'GMT'");
1709
+ }
1710
+
1711
+ /**
1712
+ * Returns a string representation of this DateTime appropriate for use in SQL Date
1713
+ * @example DateTime.utc(2014, 7, 13).toSQLDate() //=> '2014-07-13'
1714
+ * @return {string}
1715
+ */
1716
+ toSQLDate() {
1717
+ if (!this.isValid) {
1718
+ return null;
1719
+ }
1720
+ return toISODate(this, true);
1721
+ }
1722
+
1723
+ /**
1724
+ * Returns a string representation of this DateTime appropriate for use in SQL Time
1725
+ * @param {Object} opts - options
1726
+ * @param {boolean} [opts.includeZone=false] - include the zone, such as 'America/New_York'. Overrides includeOffset.
1727
+ * @param {boolean} [opts.includeOffset=true] - include the offset, such as 'Z' or '-04:00'
1728
+ * @param {boolean} [opts.includeOffsetSpace=true] - include the space between the time and the offset, such as '05:15:16.345 -04:00'
1729
+ * @example DateTime.utc().toSQL() //=> '05:15:16.345'
1730
+ * @example DateTime.now().toSQL() //=> '05:15:16.345 -04:00'
1731
+ * @example DateTime.now().toSQL({ includeOffset: false }) //=> '05:15:16.345'
1732
+ * @example DateTime.now().toSQL({ includeZone: false }) //=> '05:15:16.345 America/New_York'
1733
+ * @return {string}
1734
+ */
1735
+ toSQLTime({ includeOffset = true, includeZone = false, includeOffsetSpace = true } = {}) {
1736
+ let fmt = "HH:mm:ss.SSS";
1737
+
1738
+ if (includeZone || includeOffset) {
1739
+ if (includeOffsetSpace) {
1740
+ fmt += " ";
1741
+ }
1742
+ if (includeZone) {
1743
+ fmt += "z";
1744
+ } else if (includeOffset) {
1745
+ fmt += "ZZ";
1746
+ }
1747
+ }
1748
+
1749
+ return toTechFormat(this, fmt, true);
1750
+ }
1751
+
1752
+ /**
1753
+ * Returns a string representation of this DateTime appropriate for use in SQL DateTime
1754
+ * @param {Object} opts - options
1755
+ * @param {boolean} [opts.includeZone=false] - include the zone, such as 'America/New_York'. Overrides includeOffset.
1756
+ * @param {boolean} [opts.includeOffset=true] - include the offset, such as 'Z' or '-04:00'
1757
+ * @param {boolean} [opts.includeOffsetSpace=true] - include the space between the time and the offset, such as '05:15:16.345 -04:00'
1758
+ * @example DateTime.utc(2014, 7, 13).toSQL() //=> '2014-07-13 00:00:00.000 Z'
1759
+ * @example DateTime.local(2014, 7, 13).toSQL() //=> '2014-07-13 00:00:00.000 -04:00'
1760
+ * @example DateTime.local(2014, 7, 13).toSQL({ includeOffset: false }) //=> '2014-07-13 00:00:00.000'
1761
+ * @example DateTime.local(2014, 7, 13).toSQL({ includeZone: true }) //=> '2014-07-13 00:00:00.000 America/New_York'
1762
+ * @return {string}
1763
+ */
1764
+ toSQL(opts = {}) {
1765
+ if (!this.isValid) {
1766
+ return null;
1767
+ }
1768
+
1769
+ return `${this.toSQLDate()} ${this.toSQLTime(opts)}`;
1770
+ }
1771
+
1772
+ /**
1773
+ * Returns a string representation of this DateTime appropriate for debugging
1774
+ * @return {string}
1775
+ */
1776
+ toString() {
1777
+ return this.isValid ? this.toISO() : INVALID;
1778
+ }
1779
+
1780
+ /**
1781
+ * Returns the epoch milliseconds of this DateTime. Alias of {@link DateTime#toMillis}
1782
+ * @return {number}
1783
+ */
1784
+ valueOf() {
1785
+ return this.toMillis();
1786
+ }
1787
+
1788
+ /**
1789
+ * Returns the epoch milliseconds of this DateTime.
1790
+ * @return {number}
1791
+ */
1792
+ toMillis() {
1793
+ return this.isValid ? this.ts : NaN;
1794
+ }
1795
+
1796
+ /**
1797
+ * Returns the epoch seconds of this DateTime.
1798
+ * @return {number}
1799
+ */
1800
+ toSeconds() {
1801
+ return this.isValid ? this.ts / 1000 : NaN;
1802
+ }
1803
+
1804
+ /**
1805
+ * Returns the epoch seconds (as a whole number) of this DateTime.
1806
+ * @return {number}
1807
+ */
1808
+ toUnixInteger() {
1809
+ return this.isValid ? Math.floor(this.ts / 1000) : NaN;
1810
+ }
1811
+
1812
+ /**
1813
+ * Returns an ISO 8601 representation of this DateTime appropriate for use in JSON.
1814
+ * @return {string}
1815
+ */
1816
+ toJSON() {
1817
+ return this.toISO();
1818
+ }
1819
+
1820
+ /**
1821
+ * Returns a BSON serializable equivalent to this DateTime.
1822
+ * @return {Date}
1823
+ */
1824
+ toBSON() {
1825
+ return this.toJSDate();
1826
+ }
1827
+
1828
+ /**
1829
+ * Returns a JavaScript object with this DateTime's year, month, day, and so on.
1830
+ * @param opts - options for generating the object
1831
+ * @param {boolean} [opts.includeConfig=false] - include configuration attributes in the output
1832
+ * @example DateTime.now().toObject() //=> { year: 2017, month: 4, day: 22, hour: 20, minute: 49, second: 42, millisecond: 268 }
1833
+ * @return {Object}
1834
+ */
1835
+ toObject(opts = {}) {
1836
+ if (!this.isValid) return {};
1837
+
1838
+ const base = { ...this.c };
1839
+
1840
+ if (opts.includeConfig) {
1841
+ base.outputCalendar = this.outputCalendar;
1842
+ base.numberingSystem = this.loc.numberingSystem;
1843
+ base.locale = this.loc.locale;
1844
+ }
1845
+ return base;
1846
+ }
1847
+
1848
+ /**
1849
+ * Returns a JavaScript Date equivalent to this DateTime.
1850
+ * @return {Date}
1851
+ */
1852
+ toJSDate() {
1853
+ return new Date(this.isValid ? this.ts : NaN);
1854
+ }
1855
+
1856
+ // COMPARE
1857
+
1858
+ /**
1859
+ * Return the difference between two DateTimes as a Duration.
1860
+ * @param {DateTime} otherDateTime - the DateTime to compare this one to
1861
+ * @param {string|string[]} [unit=['milliseconds']] - the unit or array of units (such as 'hours' or 'days') to include in the duration.
1862
+ * @param {Object} opts - options that affect the creation of the Duration
1863
+ * @param {string} [opts.conversionAccuracy='casual'] - the conversion system to use
1864
+ * @example
1865
+ * var i1 = DateTime.fromISO('1982-05-25T09:45'),
1866
+ * i2 = DateTime.fromISO('1983-10-14T10:30');
1867
+ * i2.diff(i1).toObject() //=> { milliseconds: 43807500000 }
1868
+ * i2.diff(i1, 'hours').toObject() //=> { hours: 12168.75 }
1869
+ * i2.diff(i1, ['months', 'days']).toObject() //=> { months: 16, days: 19.03125 }
1870
+ * i2.diff(i1, ['months', 'days', 'hours']).toObject() //=> { months: 16, days: 19, hours: 0.75 }
1871
+ * @return {Duration}
1872
+ */
1873
+ diff(otherDateTime, unit = "milliseconds", opts = {}) {
1874
+ if (!this.isValid || !otherDateTime.isValid) {
1875
+ return Duration.invalid("created by diffing an invalid DateTime");
1876
+ }
1877
+
1878
+ const durOpts = { locale: this.locale, numberingSystem: this.numberingSystem, ...opts };
1879
+
1880
+ const units = maybeArray(unit).map(Duration.normalizeUnit),
1881
+ otherIsLater = otherDateTime.valueOf() > this.valueOf(),
1882
+ earlier = otherIsLater ? this : otherDateTime,
1883
+ later = otherIsLater ? otherDateTime : this,
1884
+ diffed = diff(earlier, later, units, durOpts);
1885
+
1886
+ return otherIsLater ? diffed.negate() : diffed;
1887
+ }
1888
+
1889
+ /**
1890
+ * Return the difference between this DateTime and right now.
1891
+ * See {@link DateTime#diff}
1892
+ * @param {string|string[]} [unit=['milliseconds']] - the unit or units units (such as 'hours' or 'days') to include in the duration
1893
+ * @param {Object} opts - options that affect the creation of the Duration
1894
+ * @param {string} [opts.conversionAccuracy='casual'] - the conversion system to use
1895
+ * @return {Duration}
1896
+ */
1897
+ diffNow(unit = "milliseconds", opts = {}) {
1898
+ return this.diff(DateTime.now(), unit, opts);
1899
+ }
1900
+
1901
+ /**
1902
+ * Return an Interval spanning between this DateTime and another DateTime
1903
+ * @param {DateTime} otherDateTime - the other end point of the Interval
1904
+ * @return {Interval}
1905
+ */
1906
+ until(otherDateTime) {
1907
+ return this.isValid ? Interval.fromDateTimes(this, otherDateTime) : this;
1908
+ }
1909
+
1910
+ /**
1911
+ * Return whether this DateTime is in the same unit of time as another DateTime.
1912
+ * Higher-order units must also be identical for this function to return `true`.
1913
+ * Note that time zones are **ignored** in this comparison, which compares the **local** calendar time. Use {@link DateTime#setZone} to convert one of the dates if needed.
1914
+ * @param {DateTime} otherDateTime - the other DateTime
1915
+ * @param {string} unit - the unit of time to check sameness on
1916
+ * @example DateTime.now().hasSame(otherDT, 'day'); //~> true if otherDT is in the same current calendar day
1917
+ * @return {boolean}
1918
+ */
1919
+ hasSame(otherDateTime, unit) {
1920
+ if (!this.isValid) return false;
1921
+
1922
+ const inputMs = otherDateTime.valueOf();
1923
+ const adjustedToZone = this.setZone(otherDateTime.zone, { keepLocalTime: true });
1924
+ return adjustedToZone.startOf(unit) <= inputMs && inputMs <= adjustedToZone.endOf(unit);
1925
+ }
1926
+
1927
+ /**
1928
+ * Equality check
1929
+ * Two DateTimes are equal if and only if they represent the same millisecond, have the same zone and location, and are both valid.
1930
+ * To compare just the millisecond values, use `+dt1 === +dt2`.
1931
+ * @param {DateTime} other - the other DateTime
1932
+ * @return {boolean}
1933
+ */
1934
+ equals(other) {
1935
+ return (
1936
+ this.isValid &&
1937
+ other.isValid &&
1938
+ this.valueOf() === other.valueOf() &&
1939
+ this.zone.equals(other.zone) &&
1940
+ this.loc.equals(other.loc)
1941
+ );
1942
+ }
1943
+
1944
+ /**
1945
+ * Returns a string representation of a this time relative to now, such as "in two days". Can only internationalize if your
1946
+ * platform supports Intl.RelativeTimeFormat. Rounds down by default.
1947
+ * @param {Object} options - options that affect the output
1948
+ * @param {DateTime} [options.base=DateTime.now()] - the DateTime to use as the basis to which this time is compared. Defaults to now.
1949
+ * @param {string} [options.style="long"] - the style of units, must be "long", "short", or "narrow"
1950
+ * @param {string|string[]} options.unit - use a specific unit or array of units; if omitted, or an array, the method will pick the best unit. Use an array or one of "years", "quarters", "months", "weeks", "days", "hours", "minutes", or "seconds"
1951
+ * @param {boolean} [options.round=true] - whether to round the numbers in the output.
1952
+ * @param {number} [options.padding=0] - padding in milliseconds. This allows you to round up the result if it fits inside the threshold. Don't use in combination with {round: false} because the decimal output will include the padding.
1953
+ * @param {string} options.locale - override the locale of this DateTime
1954
+ * @param {string} options.numberingSystem - override the numberingSystem of this DateTime. The Intl system may choose not to honor this
1955
+ * @example DateTime.now().plus({ days: 1 }).toRelative() //=> "in 1 day"
1956
+ * @example DateTime.now().setLocale("es").toRelative({ days: 1 }) //=> "dentro de 1 día"
1957
+ * @example DateTime.now().plus({ days: 1 }).toRelative({ locale: "fr" }) //=> "dans 23 heures"
1958
+ * @example DateTime.now().minus({ days: 2 }).toRelative() //=> "2 days ago"
1959
+ * @example DateTime.now().minus({ days: 2 }).toRelative({ unit: "hours" }) //=> "48 hours ago"
1960
+ * @example DateTime.now().minus({ hours: 36 }).toRelative({ round: false }) //=> "1.5 days ago"
1961
+ */
1962
+ toRelative(options = {}) {
1963
+ if (!this.isValid) return null;
1964
+ const base = options.base || DateTime.fromObject({}, { zone: this.zone }),
1965
+ padding = options.padding ? (this < base ? -options.padding : options.padding) : 0;
1966
+ let units = ["years", "months", "days", "hours", "minutes", "seconds"];
1967
+ let unit = options.unit;
1968
+ if (Array.isArray(options.unit)) {
1969
+ units = options.unit;
1970
+ unit = undefined;
1971
+ }
1972
+ return diffRelative(base, this.plus(padding), {
1973
+ ...options,
1974
+ numeric: "always",
1975
+ units,
1976
+ unit,
1977
+ });
1978
+ }
1979
+
1980
+ /**
1981
+ * Returns a string representation of this date relative to today, such as "yesterday" or "next month".
1982
+ * Only internationalizes on platforms that supports Intl.RelativeTimeFormat.
1983
+ * @param {Object} options - options that affect the output
1984
+ * @param {DateTime} [options.base=DateTime.now()] - the DateTime to use as the basis to which this time is compared. Defaults to now.
1985
+ * @param {string} options.locale - override the locale of this DateTime
1986
+ * @param {string} options.unit - use a specific unit; if omitted, the method will pick the unit. Use one of "years", "quarters", "months", "weeks", or "days"
1987
+ * @param {string} options.numberingSystem - override the numberingSystem of this DateTime. The Intl system may choose not to honor this
1988
+ * @example DateTime.now().plus({ days: 1 }).toRelativeCalendar() //=> "tomorrow"
1989
+ * @example DateTime.now().setLocale("es").plus({ days: 1 }).toRelative() //=> ""mañana"
1990
+ * @example DateTime.now().plus({ days: 1 }).toRelativeCalendar({ locale: "fr" }) //=> "demain"
1991
+ * @example DateTime.now().minus({ days: 2 }).toRelativeCalendar() //=> "2 days ago"
1992
+ */
1993
+ toRelativeCalendar(options = {}) {
1994
+ if (!this.isValid) return null;
1995
+
1996
+ return diffRelative(options.base || DateTime.fromObject({}, { zone: this.zone }), this, {
1997
+ ...options,
1998
+ numeric: "auto",
1999
+ units: ["years", "months", "days"],
2000
+ calendary: true,
2001
+ });
2002
+ }
2003
+
2004
+ /**
2005
+ * Return the min of several date times
2006
+ * @param {...DateTime} dateTimes - the DateTimes from which to choose the minimum
2007
+ * @return {DateTime} the min DateTime, or undefined if called with no argument
2008
+ */
2009
+ static min(...dateTimes) {
2010
+ if (!dateTimes.every(DateTime.isDateTime)) {
2011
+ throw new InvalidArgumentError("min requires all arguments be DateTimes");
2012
+ }
2013
+ return bestBy(dateTimes, (i) => i.valueOf(), Math.min);
2014
+ }
2015
+
2016
+ /**
2017
+ * Return the max of several date times
2018
+ * @param {...DateTime} dateTimes - the DateTimes from which to choose the maximum
2019
+ * @return {DateTime} the max DateTime, or undefined if called with no argument
2020
+ */
2021
+ static max(...dateTimes) {
2022
+ if (!dateTimes.every(DateTime.isDateTime)) {
2023
+ throw new InvalidArgumentError("max requires all arguments be DateTimes");
2024
+ }
2025
+ return bestBy(dateTimes, (i) => i.valueOf(), Math.max);
2026
+ }
2027
+
2028
+ // MISC
2029
+
2030
+ /**
2031
+ * Explain how a string would be parsed by fromFormat()
2032
+ * @param {string} text - the string to parse
2033
+ * @param {string} fmt - the format the string is expected to be in (see description)
2034
+ * @param {Object} options - options taken by fromFormat()
2035
+ * @return {Object}
2036
+ */
2037
+ static fromFormatExplain(text, fmt, options = {}) {
2038
+ const { locale = null, numberingSystem = null } = options,
2039
+ localeToUse = Locale.fromOpts({
2040
+ locale,
2041
+ numberingSystem,
2042
+ defaultToEN: true,
2043
+ });
2044
+ return explainFromTokens(localeToUse, text, fmt);
2045
+ }
2046
+
2047
+ /**
2048
+ * @deprecated use fromFormatExplain instead
2049
+ */
2050
+ static fromStringExplain(text, fmt, options = {}) {
2051
+ return DateTime.fromFormatExplain(text, fmt, options);
2052
+ }
2053
+
2054
+ // FORMAT PRESETS
2055
+
2056
+ /**
2057
+ * {@link DateTime#toLocaleString} format like 10/14/1983
2058
+ * @type {Object}
2059
+ */
2060
+ static get DATE_SHORT() {
2061
+ return Formats.DATE_SHORT;
2062
+ }
2063
+
2064
+ /**
2065
+ * {@link DateTime#toLocaleString} format like 'Oct 14, 1983'
2066
+ * @type {Object}
2067
+ */
2068
+ static get DATE_MED() {
2069
+ return Formats.DATE_MED;
2070
+ }
2071
+
2072
+ /**
2073
+ * {@link DateTime#toLocaleString} format like 'Fri, Oct 14, 1983'
2074
+ * @type {Object}
2075
+ */
2076
+ static get DATE_MED_WITH_WEEKDAY() {
2077
+ return Formats.DATE_MED_WITH_WEEKDAY;
2078
+ }
2079
+
2080
+ /**
2081
+ * {@link DateTime#toLocaleString} format like 'October 14, 1983'
2082
+ * @type {Object}
2083
+ */
2084
+ static get DATE_FULL() {
2085
+ return Formats.DATE_FULL;
2086
+ }
2087
+
2088
+ /**
2089
+ * {@link DateTime#toLocaleString} format like 'Tuesday, October 14, 1983'
2090
+ * @type {Object}
2091
+ */
2092
+ static get DATE_HUGE() {
2093
+ return Formats.DATE_HUGE;
2094
+ }
2095
+
2096
+ /**
2097
+ * {@link DateTime#toLocaleString} format like '09:30 AM'. Only 12-hour if the locale is.
2098
+ * @type {Object}
2099
+ */
2100
+ static get TIME_SIMPLE() {
2101
+ return Formats.TIME_SIMPLE;
2102
+ }
2103
+
2104
+ /**
2105
+ * {@link DateTime#toLocaleString} format like '09:30:23 AM'. Only 12-hour if the locale is.
2106
+ * @type {Object}
2107
+ */
2108
+ static get TIME_WITH_SECONDS() {
2109
+ return Formats.TIME_WITH_SECONDS;
2110
+ }
2111
+
2112
+ /**
2113
+ * {@link DateTime#toLocaleString} format like '09:30:23 AM EDT'. Only 12-hour if the locale is.
2114
+ * @type {Object}
2115
+ */
2116
+ static get TIME_WITH_SHORT_OFFSET() {
2117
+ return Formats.TIME_WITH_SHORT_OFFSET;
2118
+ }
2119
+
2120
+ /**
2121
+ * {@link DateTime#toLocaleString} format like '09:30:23 AM Eastern Daylight Time'. Only 12-hour if the locale is.
2122
+ * @type {Object}
2123
+ */
2124
+ static get TIME_WITH_LONG_OFFSET() {
2125
+ return Formats.TIME_WITH_LONG_OFFSET;
2126
+ }
2127
+
2128
+ /**
2129
+ * {@link DateTime#toLocaleString} format like '09:30', always 24-hour.
2130
+ * @type {Object}
2131
+ */
2132
+ static get TIME_24_SIMPLE() {
2133
+ return Formats.TIME_24_SIMPLE;
2134
+ }
2135
+
2136
+ /**
2137
+ * {@link DateTime#toLocaleString} format like '09:30:23', always 24-hour.
2138
+ * @type {Object}
2139
+ */
2140
+ static get TIME_24_WITH_SECONDS() {
2141
+ return Formats.TIME_24_WITH_SECONDS;
2142
+ }
2143
+
2144
+ /**
2145
+ * {@link DateTime#toLocaleString} format like '09:30:23 EDT', always 24-hour.
2146
+ * @type {Object}
2147
+ */
2148
+ static get TIME_24_WITH_SHORT_OFFSET() {
2149
+ return Formats.TIME_24_WITH_SHORT_OFFSET;
2150
+ }
2151
+
2152
+ /**
2153
+ * {@link DateTime#toLocaleString} format like '09:30:23 Eastern Daylight Time', always 24-hour.
2154
+ * @type {Object}
2155
+ */
2156
+ static get TIME_24_WITH_LONG_OFFSET() {
2157
+ return Formats.TIME_24_WITH_LONG_OFFSET;
2158
+ }
2159
+
2160
+ /**
2161
+ * {@link DateTime#toLocaleString} format like '10/14/1983, 9:30 AM'. Only 12-hour if the locale is.
2162
+ * @type {Object}
2163
+ */
2164
+ static get DATETIME_SHORT() {
2165
+ return Formats.DATETIME_SHORT;
2166
+ }
2167
+
2168
+ /**
2169
+ * {@link DateTime#toLocaleString} format like '10/14/1983, 9:30:33 AM'. Only 12-hour if the locale is.
2170
+ * @type {Object}
2171
+ */
2172
+ static get DATETIME_SHORT_WITH_SECONDS() {
2173
+ return Formats.DATETIME_SHORT_WITH_SECONDS;
2174
+ }
2175
+
2176
+ /**
2177
+ * {@link DateTime#toLocaleString} format like 'Oct 14, 1983, 9:30 AM'. Only 12-hour if the locale is.
2178
+ * @type {Object}
2179
+ */
2180
+ static get DATETIME_MED() {
2181
+ return Formats.DATETIME_MED;
2182
+ }
2183
+
2184
+ /**
2185
+ * {@link DateTime#toLocaleString} format like 'Oct 14, 1983, 9:30:33 AM'. Only 12-hour if the locale is.
2186
+ * @type {Object}
2187
+ */
2188
+ static get DATETIME_MED_WITH_SECONDS() {
2189
+ return Formats.DATETIME_MED_WITH_SECONDS;
2190
+ }
2191
+
2192
+ /**
2193
+ * {@link DateTime#toLocaleString} format like 'Fri, 14 Oct 1983, 9:30 AM'. Only 12-hour if the locale is.
2194
+ * @type {Object}
2195
+ */
2196
+ static get DATETIME_MED_WITH_WEEKDAY() {
2197
+ return Formats.DATETIME_MED_WITH_WEEKDAY;
2198
+ }
2199
+
2200
+ /**
2201
+ * {@link DateTime#toLocaleString} format like 'October 14, 1983, 9:30 AM EDT'. Only 12-hour if the locale is.
2202
+ * @type {Object}
2203
+ */
2204
+ static get DATETIME_FULL() {
2205
+ return Formats.DATETIME_FULL;
2206
+ }
2207
+
2208
+ /**
2209
+ * {@link DateTime#toLocaleString} format like 'October 14, 1983, 9:30:33 AM EDT'. Only 12-hour if the locale is.
2210
+ * @type {Object}
2211
+ */
2212
+ static get DATETIME_FULL_WITH_SECONDS() {
2213
+ return Formats.DATETIME_FULL_WITH_SECONDS;
2214
+ }
2215
+
2216
+ /**
2217
+ * {@link DateTime#toLocaleString} format like 'Friday, October 14, 1983, 9:30 AM Eastern Daylight Time'. Only 12-hour if the locale is.
2218
+ * @type {Object}
2219
+ */
2220
+ static get DATETIME_HUGE() {
2221
+ return Formats.DATETIME_HUGE;
2222
+ }
2223
+
2224
+ /**
2225
+ * {@link DateTime#toLocaleString} format like 'Friday, October 14, 1983, 9:30:33 AM Eastern Daylight Time'. Only 12-hour if the locale is.
2226
+ * @type {Object}
2227
+ */
2228
+ static get DATETIME_HUGE_WITH_SECONDS() {
2229
+ return Formats.DATETIME_HUGE_WITH_SECONDS;
2230
+ }
2231
+ }
2232
+
2233
+ /**
2234
+ * @private
2235
+ */
2236
+ export function friendlyDateTime(dateTimeish) {
2237
+ if (DateTime.isDateTime(dateTimeish)) {
2238
+ return dateTimeish;
2239
+ } else if (dateTimeish && dateTimeish.valueOf && isNumber(dateTimeish.valueOf())) {
2240
+ return DateTime.fromJSDate(dateTimeish);
2241
+ } else if (dateTimeish && typeof dateTimeish === "object") {
2242
+ return DateTime.fromObject(dateTimeish);
2243
+ } else {
2244
+ throw new InvalidArgumentError(
2245
+ `Unknown datetime argument: ${dateTimeish}, of type ${typeof dateTimeish}`
2246
+ );
2247
+ }
2248
+ }