parse.js 28 KB

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