@cloudsnorkel/cdk-github-runners 0.14.24 → 0.15.1

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