1 | import { defaultLocale } from "./_lib/defaultLocale.js";
|
2 | import { longFormatters } from "./_lib/format/longFormatters.js";
|
3 | import {
|
4 | isProtectedDayOfYearToken,
|
5 | isProtectedWeekYearToken,
|
6 | warnOrThrowProtectedError,
|
7 | } from "./_lib/protectedTokens.js";
|
8 | import { constructFrom } from "./constructFrom.js";
|
9 | import { getDefaultOptions } from "./getDefaultOptions.js";
|
10 | import { toDate } from "./toDate.js";
|
11 |
|
12 | import { DateTimezoneSetter } from "./parse/_lib/Setter.js";
|
13 | import { parsers } from "./parse/_lib/parsers.js";
|
14 |
|
15 | // Rexports of internal for libraries to use.
|
16 | // See: https://github.com/date-fns/date-fns/issues/3638#issuecomment-1877082874
|
17 | export { longFormatters, parsers };
|
18 |
|
19 | /**
|
20 | * The {@link parse} function options.
|
21 | */
|
22 |
|
23 | // This RegExp consists of three parts separated by `|`:
|
24 | // - [yYQqMLwIdDecihHKkms]o matches any available ordinal number token
|
25 | // (one of the certain letters followed by `o`)
|
26 | // - (\w)\1* matches any sequences of the same letter
|
27 | // - '' matches two quote characters in a row
|
28 | // - '(''|[^'])+('|$) matches anything surrounded by two quote characters ('),
|
29 | // except a single quote symbol, which ends the sequence.
|
30 | // Two quote characters do not end the sequence.
|
31 | // If there is no matching single quote
|
32 | // then the sequence will continue until the end of the string.
|
33 | // - . matches any single character unmatched by previous parts of the RegExps
|
34 | const formattingTokensRegExp =
|
35 | /[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g;
|
36 |
|
37 | // This RegExp catches symbols escaped by quotes, and also
|
38 | // sequences of symbols P, p, and the combinations like `PPPPPPPppppp`
|
39 | const longFormattingTokensRegExp = /P+p+|P+|p+|''|'(''|[^'])+('|$)|./g;
|
40 |
|
41 | const escapedStringRegExp = /^'([^]*?)'?$/;
|
42 | const doubleQuoteRegExp = /''/g;
|
43 |
|
44 | const notWhitespaceRegExp = /\S/;
|
45 | const unescapedLatinCharacterRegExp = /[a-zA-Z]/;
|
46 |
|
47 | /**
|
48 | * @name parse
|
49 | * @category Common Helpers
|
50 | * @summary Parse the date.
|
51 | *
|
52 | * @description
|
53 | * Return the date parsed from string using the given format string.
|
54 | *
|
55 | * > ⚠️ Please note that the `format` tokens differ from Moment.js and other libraries.
|
56 | * > See: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md
|
57 | *
|
58 | * The characters in the format string wrapped between two single quotes characters (') are escaped.
|
59 | * Two single quotes in a row, whether inside or outside a quoted sequence, represent a 'real' single quote.
|
60 | *
|
61 | * Format of the format string is based on Unicode Technical Standard #35:
|
62 | * https://www.unicode.org/reports/tr35/tr35-dates.html#Date_Field_Symbol_Table
|
63 | * with a few additions (see note 5 below the table).
|
64 | *
|
65 | * Not all tokens are compatible. Combinations that don't make sense or could lead to bugs are prohibited
|
66 | * and will throw `RangeError`. For example usage of 24-hour format token with AM/PM token will throw an exception:
|
67 | *
|
68 | * ```javascript
|
69 | * parse('23 AM', 'HH a', new Date())
|
70 | * //=> RangeError: The format string mustn't contain `HH` and `a` at the same time
|
71 | * ```
|
72 | *
|
73 | * See the compatibility table: https://docs.google.com/spreadsheets/d/e/2PACX-1vQOPU3xUhplll6dyoMmVUXHKl_8CRDs6_ueLmex3SoqwhuolkuN3O05l4rqx5h1dKX8eb46Ul-CCSrq/pubhtml?gid=0&single=true
|
74 | *
|
75 | * Accepted format string patterns:
|
76 | * | Unit |Prior| Pattern | Result examples | Notes |
|
77 | * |---------------------------------|-----|---------|-----------------------------------|-------|
|
78 | * | Era | 140 | G..GGG | AD, BC | |
|
79 | * | | | GGGG | Anno Domini, Before Christ | 2 |
|
80 | * | | | GGGGG | A, B | |
|
81 | * | Calendar year | 130 | y | 44, 1, 1900, 2017, 9999 | 4 |
|
82 | * | | | yo | 44th, 1st, 1900th, 9999999th | 4,5 |
|
83 | * | | | yy | 44, 01, 00, 17 | 4 |
|
84 | * | | | yyy | 044, 001, 123, 999 | 4 |
|
85 | * | | | yyyy | 0044, 0001, 1900, 2017 | 4 |
|
86 | * | | | yyyyy | ... | 2,4 |
|
87 | * | Local week-numbering year | 130 | Y | 44, 1, 1900, 2017, 9000 | 4 |
|
88 | * | | | Yo | 44th, 1st, 1900th, 9999999th | 4,5 |
|
89 | * | | | YY | 44, 01, 00, 17 | 4,6 |
|
90 | * | | | YYY | 044, 001, 123, 999 | 4 |
|
91 | * | | | YYYY | 0044, 0001, 1900, 2017 | 4,6 |
|
92 | * | | | YYYYY | ... | 2,4 |
|
93 | * | ISO week-numbering year | 130 | R | -43, 1, 1900, 2017, 9999, -9999 | 4,5 |
|
94 | * | | | RR | -43, 01, 00, 17 | 4,5 |
|
95 | * | | | RRR | -043, 001, 123, 999, -999 | 4,5 |
|
96 | * | | | RRRR | -0043, 0001, 2017, 9999, -9999 | 4,5 |
|
97 | * | | | RRRRR | ... | 2,4,5 |
|
98 | * | Extended year | 130 | u | -43, 1, 1900, 2017, 9999, -999 | 4 |
|
99 | * | | | uu | -43, 01, 99, -99 | 4 |
|
100 | * | | | uuu | -043, 001, 123, 999, -999 | 4 |
|
101 | * | | | uuuu | -0043, 0001, 2017, 9999, -9999 | 4 |
|
102 | * | | | uuuuu | ... | 2,4 |
|
103 | * | Quarter (formatting) | 120 | Q | 1, 2, 3, 4 | |
|
104 | * | | | Qo | 1st, 2nd, 3rd, 4th | 5 |
|
105 | * | | | QQ | 01, 02, 03, 04 | |
|
106 | * | | | QQQ | Q1, Q2, Q3, Q4 | |
|
107 | * | | | QQQQ | 1st quarter, 2nd quarter, ... | 2 |
|
108 | * | | | QQQQQ | 1, 2, 3, 4 | 4 |
|
109 | * | Quarter (stand-alone) | 120 | q | 1, 2, 3, 4 | |
|
110 | * | | | qo | 1st, 2nd, 3rd, 4th | 5 |
|
111 | * | | | qq | 01, 02, 03, 04 | |
|
112 | * | | | qqq | Q1, Q2, Q3, Q4 | |
|
113 | * | | | qqqq | 1st quarter, 2nd quarter, ... | 2 |
|
114 | * | | | qqqqq | 1, 2, 3, 4 | 3 |
|
115 | * | Month (formatting) | 110 | M | 1, 2, ..., 12 | |
|
116 | * | | | Mo | 1st, 2nd, ..., 12th | 5 |
|
117 | * | | | MM | 01, 02, ..., 12 | |
|
118 | * | | | MMM | Jan, Feb, ..., Dec | |
|
119 | * | | | MMMM | January, February, ..., December | 2 |
|
120 | * | | | MMMMM | J, F, ..., D | |
|
121 | * | Month (stand-alone) | 110 | L | 1, 2, ..., 12 | |
|
122 | * | | | Lo | 1st, 2nd, ..., 12th | 5 |
|
123 | * | | | LL | 01, 02, ..., 12 | |
|
124 | * | | | LLL | Jan, Feb, ..., Dec | |
|
125 | * | | | LLLL | January, February, ..., December | 2 |
|
126 | * | | | LLLLL | J, F, ..., D | |
|
127 | * | Local week of year | 100 | w | 1, 2, ..., 53 | |
|
128 | * | | | wo | 1st, 2nd, ..., 53th | 5 |
|
129 | * | | | ww | 01, 02, ..., 53 | |
|
130 | * | ISO week of year | 100 | I | 1, 2, ..., 53 | 5 |
|
131 | * | | | Io | 1st, 2nd, ..., 53th | 5 |
|
132 | * | | | II | 01, 02, ..., 53 | 5 |
|
133 | * | Day of month | 90 | d | 1, 2, ..., 31 | |
|
134 | * | | | do | 1st, 2nd, ..., 31st | 5 |
|
135 | * | | | dd | 01, 02, ..., 31 | |
|
136 | * | Day of year | 90 | D | 1, 2, ..., 365, 366 | 7 |
|
137 | * | | | Do | 1st, 2nd, ..., 365th, 366th | 5 |
|
138 | * | | | DD | 01, 02, ..., 365, 366 | 7 |
|
139 | * | | | DDD | 001, 002, ..., 365, 366 | |
|
140 | * | | | DDDD | ... | 2 |
|
141 | * | Day of week (formatting) | 90 | E..EEE | Mon, Tue, Wed, ..., Sun | |
|
142 | * | | | EEEE | Monday, Tuesday, ..., Sunday | 2 |
|
143 | * | | | EEEEE | M, T, W, T, F, S, S | |
|
144 | * | | | EEEEEE | Mo, Tu, We, Th, Fr, Sa, Su | |
|
145 | * | ISO day of week (formatting) | 90 | i | 1, 2, 3, ..., 7 | 5 |
|
146 | * | | | io | 1st, 2nd, ..., 7th | 5 |
|
147 | * | | | ii | 01, 02, ..., 07 | 5 |
|
148 | * | | | iii | Mon, Tue, Wed, ..., Sun | 5 |
|
149 | * | | | iiii | Monday, Tuesday, ..., Sunday | 2,5 |
|
150 | * | | | iiiii | M, T, W, T, F, S, S | 5 |
|
151 | * | | | iiiiii | Mo, Tu, We, Th, Fr, Sa, Su | 5 |
|
152 | * | Local day of week (formatting) | 90 | e | 2, 3, 4, ..., 1 | |
|
153 | * | | | eo | 2nd, 3rd, ..., 1st | 5 |
|
154 | * | | | ee | 02, 03, ..., 01 | |
|
155 | * | | | eee | Mon, Tue, Wed, ..., Sun | |
|
156 | * | | | eeee | Monday, Tuesday, ..., Sunday | 2 |
|
157 | * | | | eeeee | M, T, W, T, F, S, S | |
|
158 | * | | | eeeeee | Mo, Tu, We, Th, Fr, Sa, Su | |
|
159 | * | Local day of week (stand-alone) | 90 | c | 2, 3, 4, ..., 1 | |
|
160 | * | | | co | 2nd, 3rd, ..., 1st | 5 |
|
161 | * | | | cc | 02, 03, ..., 01 | |
|
162 | * | | | ccc | Mon, Tue, Wed, ..., Sun | |
|
163 | * | | | cccc | Monday, Tuesday, ..., Sunday | 2 |
|
164 | * | | | ccccc | M, T, W, T, F, S, S | |
|
165 | * | | | cccccc | Mo, Tu, We, Th, Fr, Sa, Su | |
|
166 | * | AM, PM | 80 | a..aaa | AM, PM | |
|
167 | * | | | aaaa | a.m., p.m. | 2 |
|
168 | * | | | aaaaa | a, p | |
|
169 | * | AM, PM, noon, midnight | 80 | b..bbb | AM, PM, noon, midnight | |
|
170 | * | | | bbbb | a.m., p.m., noon, midnight | 2 |
|
171 | * | | | bbbbb | a, p, n, mi | |
|
172 | * | Flexible day period | 80 | B..BBB | at night, in the morning, ... | |
|
173 | * | | | BBBB | at night, in the morning, ... | 2 |
|
174 | * | | | BBBBB | at night, in the morning, ... | |
|
175 | * | Hour [1-12] | 70 | h | 1, 2, ..., 11, 12 | |
|
176 | * | | | ho | 1st, 2nd, ..., 11th, 12th | 5 |
|
177 | * | | | hh | 01, 02, ..., 11, 12 | |
|
178 | * | Hour [0-23] | 70 | H | 0, 1, 2, ..., 23 | |
|
179 | * | | | Ho | 0th, 1st, 2nd, ..., 23rd | 5 |
|
180 | * | | | HH | 00, 01, 02, ..., 23 | |
|
181 | * | Hour [0-11] | 70 | K | 1, 2, ..., 11, 0 | |
|
182 | * | | | Ko | 1st, 2nd, ..., 11th, 0th | 5 |
|
183 | * | | | KK | 01, 02, ..., 11, 00 | |
|
184 | * | Hour [1-24] | 70 | k | 24, 1, 2, ..., 23 | |
|
185 | * | | | ko | 24th, 1st, 2nd, ..., 23rd | 5 |
|
186 | * | | | kk | 24, 01, 02, ..., 23 | |
|
187 | * | Minute | 60 | m | 0, 1, ..., 59 | |
|
188 | * | | | mo | 0th, 1st, ..., 59th | 5 |
|
189 | * | | | mm | 00, 01, ..., 59 | |
|
190 | * | Second | 50 | s | 0, 1, ..., 59 | |
|
191 | * | | | so | 0th, 1st, ..., 59th | 5 |
|
192 | * | | | ss | 00, 01, ..., 59 | |
|
193 | * | Seconds timestamp | 40 | t | 512969520 | |
|
194 | * | | | tt | ... | 2 |
|
195 | * | Fraction of second | 30 | S | 0, 1, ..., 9 | |
|
196 | * | | | SS | 00, 01, ..., 99 | |
|
197 | * | | | SSS | 000, 001, ..., 999 | |
|
198 | * | | | SSSS | ... | 2 |
|
199 | * | Milliseconds timestamp | 20 | T | 512969520900 | |
|
200 | * | | | TT | ... | 2 |
|
201 | * | Timezone (ISO-8601 w/ Z) | 10 | X | -08, +0530, Z | |
|
202 | * | | | XX | -0800, +0530, Z | |
|
203 | * | | | XXX | -08:00, +05:30, Z | |
|
204 | * | | | XXXX | -0800, +0530, Z, +123456 | 2 |
|
205 | * | | | XXXXX | -08:00, +05:30, Z, +12:34:56 | |
|
206 | * | Timezone (ISO-8601 w/o Z) | 10 | x | -08, +0530, +00 | |
|
207 | * | | | xx | -0800, +0530, +0000 | |
|
208 | * | | | xxx | -08:00, +05:30, +00:00 | 2 |
|
209 | * | | | xxxx | -0800, +0530, +0000, +123456 | |
|
210 | * | | | xxxxx | -08:00, +05:30, +00:00, +12:34:56 | |
|
211 | * | Long localized date | NA | P | 05/29/1453 | 5,8 |
|
212 | * | | | PP | May 29, 1453 | |
|
213 | * | | | PPP | May 29th, 1453 | |
|
214 | * | | | PPPP | Sunday, May 29th, 1453 | 2,5,8 |
|
215 | * | Long localized time | NA | p | 12:00 AM | 5,8 |
|
216 | * | | | pp | 12:00:00 AM | |
|
217 | * | Combination of date and time | NA | Pp | 05/29/1453, 12:00 AM | |
|
218 | * | | | PPpp | May 29, 1453, 12:00:00 AM | |
|
219 | * | | | PPPpp | May 29th, 1453 at ... | |
|
220 | * | | | PPPPpp | Sunday, May 29th, 1453 at ... | 2,5,8 |
|
221 | * Notes:
|
222 | * 1. "Formatting" units (e.g. formatting quarter) in the default en-US locale
|
223 | * are the same as "stand-alone" units, but are different in some languages.
|
224 | * "Formatting" units are declined according to the rules of the language
|
225 | * in the context of a date. "Stand-alone" units are always nominative singular.
|
226 | * In `format` function, they will produce different result:
|
227 | *
|
228 | * `format(new Date(2017, 10, 6), 'do LLLL', {locale: cs}) //=> '6. listopad'`
|
229 | *
|
230 | * `format(new Date(2017, 10, 6), 'do MMMM', {locale: cs}) //=> '6. listopadu'`
|
231 | *
|
232 | * `parse` will try to match both formatting and stand-alone units interchangeably.
|
233 | *
|
234 | * 2. Any sequence of the identical letters is a pattern, unless it is escaped by
|
235 | * the single quote characters (see below).
|
236 | * If the sequence is longer than listed in table:
|
237 | * - for numerical units (`yyyyyyyy`) `parse` will try to match a number
|
238 | * as wide as the sequence
|
239 | * - for text units (`MMMMMMMM`) `parse` will try to match the widest variation of the unit.
|
240 | * These variations are marked with "2" in the last column of the table.
|
241 | *
|
242 | * 3. `QQQQQ` and `qqqqq` could be not strictly numerical in some locales.
|
243 | * These tokens represent the shortest form of the quarter.
|
244 | *
|
245 | * 4. The main difference between `y` and `u` patterns are B.C. years:
|
246 | *
|
247 | * | Year | `y` | `u` |
|
248 | * |------|-----|-----|
|
249 | * | AC 1 | 1 | 1 |
|
250 | * | BC 1 | 1 | 0 |
|
251 | * | BC 2 | 2 | -1 |
|
252 | *
|
253 | * Also `yy` will try to guess the century of two digit year by proximity with `referenceDate`:
|
254 | *
|
255 | * `parse('50', 'yy', new Date(2018, 0, 1)) //=> Sat Jan 01 2050 00:00:00`
|
256 | *
|
257 | * `parse('75', 'yy', new Date(2018, 0, 1)) //=> Wed Jan 01 1975 00:00:00`
|
258 | *
|
259 | * while `uu` will just assign the year as is:
|
260 | *
|
261 | * `parse('50', 'uu', new Date(2018, 0, 1)) //=> Sat Jan 01 0050 00:00:00`
|
262 | *
|
263 | * `parse('75', 'uu', new Date(2018, 0, 1)) //=> Tue Jan 01 0075 00:00:00`
|
264 | *
|
265 | * The same difference is true for local and ISO week-numbering years (`Y` and `R`),
|
266 | * except local week-numbering years are dependent on `options.weekStartsOn`
|
267 | * and `options.firstWeekContainsDate` (compare [setISOWeekYear](https://date-fns.org/docs/setISOWeekYear)
|
268 | * and [setWeekYear](https://date-fns.org/docs/setWeekYear)).
|
269 | *
|
270 | * 5. These patterns are not in the Unicode Technical Standard #35:
|
271 | * - `i`: ISO day of week
|
272 | * - `I`: ISO week of year
|
273 | * - `R`: ISO week-numbering year
|
274 | * - `o`: ordinal number modifier
|
275 | * - `P`: long localized date
|
276 | * - `p`: long localized time
|
277 | *
|
278 | * 6. `YY` and `YYYY` tokens represent week-numbering years but they are often confused with years.
|
279 | * You should enable `options.useAdditionalWeekYearTokens` to use them. See: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md
|
280 | *
|
281 | * 7. `D` and `DD` tokens represent days of the year but they are often confused with days of the month.
|
282 | * You should enable `options.useAdditionalDayOfYearTokens` to use them. See: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md
|
283 | *
|
284 | * 8. `P+` tokens do not have a defined priority since they are merely aliases to other tokens based
|
285 | * on the given locale.
|
286 | *
|
287 | * using `en-US` locale: `P` => `MM/dd/yyyy`
|
288 | * using `en-US` locale: `p` => `hh:mm a`
|
289 | * using `pt-BR` locale: `P` => `dd/MM/yyyy`
|
290 | * using `pt-BR` locale: `p` => `HH:mm`
|
291 | *
|
292 | * Values will be assigned to the date in the descending order of its unit's priority.
|
293 | * Units of an equal priority overwrite each other in the order of appearance.
|
294 | *
|
295 | * If no values of higher priority are parsed (e.g. when parsing string 'January 1st' without a year),
|
296 | * the values will be taken from 3rd argument `referenceDate` which works as a context of parsing.
|
297 | *
|
298 | * `referenceDate` must be passed for correct work of the function.
|
299 | * If you're not sure which `referenceDate` to supply, create a new instance of Date:
|
300 | * `parse('02/11/2014', 'MM/dd/yyyy', new Date())`
|
301 | * In this case parsing will be done in the context of the current date.
|
302 | * If `referenceDate` is `Invalid Date` or a value not convertible to valid `Date`,
|
303 | * then `Invalid Date` will be returned.
|
304 | *
|
305 | * The result may vary by locale.
|
306 | *
|
307 | * If `formatString` matches with `dateString` but does not provides tokens, `referenceDate` will be returned.
|
308 | *
|
309 | * If parsing failed, `Invalid Date` will be returned.
|
310 | * Invalid Date is a Date, whose time value is NaN.
|
311 | * Time value of Date: http://es5.github.io/#x15.9.1.1
|
312 | *
|
313 | * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).
|
314 | * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.
|
315 | *
|
316 | * @param dateStr - The string to parse
|
317 | * @param formatStr - The string of tokens
|
318 | * @param referenceDate - defines values missing from the parsed dateString
|
319 | * @param options - An object with options.
|
320 | * see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md
|
321 | * see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md
|
322 | *
|
323 | * @returns The parsed date
|
324 | *
|
325 | * @throws `options.locale` must contain `match` property
|
326 | * @throws use `yyyy` instead of `YYYY` for formatting years using [format provided] to the input [input provided]; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md
|
327 | * @throws use `yy` instead of `YY` for formatting years using [format provided] to the input [input provided]; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md
|
328 | * @throws use `d` instead of `D` for formatting days of the month using [format provided] to the input [input provided]; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md
|
329 | * @throws use `dd` instead of `DD` for formatting days of the month using [format provided] to the input [input provided]; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md
|
330 | * @throws format string contains an unescaped latin alphabet character
|
331 | *
|
332 | * @example
|
333 | * // Parse 11 February 2014 from middle-endian format:
|
334 | * var result = parse('02/11/2014', 'MM/dd/yyyy', new Date())
|
335 | * //=> Tue Feb 11 2014 00:00:00
|
336 | *
|
337 | * @example
|
338 | * // Parse 28th of February in Esperanto locale in the context of 2010 year:
|
339 | * import eo from 'date-fns/locale/eo'
|
340 | * var result = parse('28-a de februaro', "do 'de' MMMM", new Date(2010, 0, 1), {
|
341 | * locale: eo
|
342 | * })
|
343 | * //=> Sun Feb 28 2010 00:00:00
|
344 | */
|
345 | export function parse(dateStr, formatStr, referenceDate, options) {
|
346 | const invalidDate = () => constructFrom(options?.in || referenceDate, NaN);
|
347 | const defaultOptions = getDefaultOptions();
|
348 | const locale = options?.locale ?? defaultOptions.locale ?? defaultLocale;
|
349 |
|
350 | const firstWeekContainsDate =
|
351 | options?.firstWeekContainsDate ??
|
352 | options?.locale?.options?.firstWeekContainsDate ??
|
353 | defaultOptions.firstWeekContainsDate ??
|
354 | defaultOptions.locale?.options?.firstWeekContainsDate ??
|
355 | 1;
|
356 |
|
357 | const weekStartsOn =
|
358 | options?.weekStartsOn ??
|
359 | options?.locale?.options?.weekStartsOn ??
|
360 | defaultOptions.weekStartsOn ??
|
361 | defaultOptions.locale?.options?.weekStartsOn ??
|
362 | 0;
|
363 |
|
364 | if (!formatStr)
|
365 | return dateStr ? invalidDate() : toDate(referenceDate, options?.in);
|
366 |
|
367 | const subFnOptions = {
|
368 | firstWeekContainsDate,
|
369 | weekStartsOn,
|
370 | locale,
|
371 | };
|
372 |
|
373 | // If timezone isn't specified, it will try to use the context or
|
374 | // the reference date and fallback to the system time zone.
|
375 | const setters = [new DateTimezoneSetter(options?.in, referenceDate)];
|
376 |
|
377 | const tokens = formatStr
|
378 | .match(longFormattingTokensRegExp)
|
379 | .map((substring) => {
|
380 | const firstCharacter = substring[0];
|
381 | if (firstCharacter in longFormatters) {
|
382 | const longFormatter = longFormatters[firstCharacter];
|
383 | return longFormatter(substring, locale.formatLong);
|
384 | }
|
385 | return substring;
|
386 | })
|
387 | .join("")
|
388 | .match(formattingTokensRegExp);
|
389 |
|
390 | const usedTokens = [];
|
391 |
|
392 | for (let token of tokens) {
|
393 | if (
|
394 | !options?.useAdditionalWeekYearTokens &&
|
395 | isProtectedWeekYearToken(token)
|
396 | ) {
|
397 | warnOrThrowProtectedError(token, formatStr, dateStr);
|
398 | }
|
399 | if (
|
400 | !options?.useAdditionalDayOfYearTokens &&
|
401 | isProtectedDayOfYearToken(token)
|
402 | ) {
|
403 | warnOrThrowProtectedError(token, formatStr, dateStr);
|
404 | }
|
405 |
|
406 | const firstCharacter = token[0];
|
407 | const parser = parsers[firstCharacter];
|
408 | if (parser) {
|
409 | const { incompatibleTokens } = parser;
|
410 | if (Array.isArray(incompatibleTokens)) {
|
411 | const incompatibleToken = usedTokens.find(
|
412 | (usedToken) =>
|
413 | incompatibleTokens.includes(usedToken.token) ||
|
414 | usedToken.token === firstCharacter,
|
415 | );
|
416 | if (incompatibleToken) {
|
417 | throw new RangeError(
|
418 | `The format string mustn't contain \`${incompatibleToken.fullToken}\` and \`${token}\` at the same time`,
|
419 | );
|
420 | }
|
421 | } else if (parser.incompatibleTokens === "*" && usedTokens.length > 0) {
|
422 | throw new RangeError(
|
423 | `The format string mustn't contain \`${token}\` and any other token at the same time`,
|
424 | );
|
425 | }
|
426 |
|
427 | usedTokens.push({ token: firstCharacter, fullToken: token });
|
428 |
|
429 | const parseResult = parser.run(
|
430 | dateStr,
|
431 | token,
|
432 | locale.match,
|
433 | subFnOptions,
|
434 | );
|
435 |
|
436 | if (!parseResult) {
|
437 | return invalidDate();
|
438 | }
|
439 |
|
440 | setters.push(parseResult.setter);
|
441 |
|
442 | dateStr = parseResult.rest;
|
443 | } else {
|
444 | if (firstCharacter.match(unescapedLatinCharacterRegExp)) {
|
445 | throw new RangeError(
|
446 | "Format string contains an unescaped latin alphabet character `" +
|
447 | firstCharacter +
|
448 | "`",
|
449 | );
|
450 | }
|
451 |
|
452 | // Replace two single quote characters with one single quote character
|
453 | if (token === "''") {
|
454 | token = "'";
|
455 | } else if (firstCharacter === "'") {
|
456 | token = cleanEscapedString(token);
|
457 | }
|
458 |
|
459 | // Cut token from string, or, if string doesn't match the token, return Invalid Date
|
460 | if (dateStr.indexOf(token) === 0) {
|
461 | dateStr = dateStr.slice(token.length);
|
462 | } else {
|
463 | return invalidDate();
|
464 | }
|
465 | }
|
466 | }
|
467 |
|
468 | // Check if the remaining input contains something other than whitespace
|
469 | if (dateStr.length > 0 && notWhitespaceRegExp.test(dateStr)) {
|
470 | return invalidDate();
|
471 | }
|
472 |
|
473 | const uniquePrioritySetters = setters
|
474 | .map((setter) => setter.priority)
|
475 | .sort((a, b) => b - a)
|
476 | .filter((priority, index, array) => array.indexOf(priority) === index)
|
477 | .map((priority) =>
|
478 | setters
|
479 | .filter((setter) => setter.priority === priority)
|
480 | .sort((a, b) => b.subPriority - a.subPriority),
|
481 | )
|
482 | .map((setterArray) => setterArray[0]);
|
483 |
|
484 | let date = toDate(referenceDate, options?.in);
|
485 |
|
486 | if (isNaN(+date)) return invalidDate();
|
487 |
|
488 | const flags = {};
|
489 | for (const setter of uniquePrioritySetters) {
|
490 | if (!setter.validate(date, subFnOptions)) {
|
491 | return invalidDate();
|
492 | }
|
493 |
|
494 | const result = setter.set(date, flags, subFnOptions);
|
495 | // Result is tuple (date, flags)
|
496 | if (Array.isArray(result)) {
|
497 | date = result[0];
|
498 | Object.assign(flags, result[1]);
|
499 | // Result is date
|
500 | } else {
|
501 | date = result;
|
502 | }
|
503 | }
|
504 |
|
505 | return date;
|
506 | }
|
507 |
|
508 | function cleanEscapedString(input) {
|
509 | return input.match(escapedStringRegExp)[1].replace(doubleQuoteRegExp, "'");
|
510 | }
|
511 |
|
512 | // Fallback for modularized imports:
|
513 | export default parse;
|