index.js 31 KB

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