format.cjs 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440
  1. "use strict";
  2. exports.format = exports.formatDate = format;
  3. Object.defineProperty(exports, "formatters", {
  4. enumerable: true,
  5. get: function () {
  6. return _index3.formatters;
  7. },
  8. });
  9. Object.defineProperty(exports, "longFormatters", {
  10. enumerable: true,
  11. get: function () {
  12. return _index4.longFormatters;
  13. },
  14. });
  15. var _index = require("./_lib/defaultLocale.cjs");
  16. var _index2 = require("./_lib/defaultOptions.cjs");
  17. var _index3 = require("./_lib/format/formatters.cjs");
  18. var _index4 = require("./_lib/format/longFormatters.cjs");
  19. var _index5 = require("./_lib/protectedTokens.cjs");
  20. var _index6 = require("./isValid.cjs");
  21. var _index7 = require("./toDate.cjs");
  22. // Rexports of internal for libraries to use.
  23. // See: https://github.com/date-fns/date-fns/issues/3638#issuecomment-1877082874
  24. // This RegExp consists of three parts separated by `|`:
  25. // - [yYQqMLwIdDecihHKkms]o matches any available ordinal number token
  26. // (one of the certain letters followed by `o`)
  27. // - (\w)\1* matches any sequences of the same letter
  28. // - '' matches two quote characters in a row
  29. // - '(''|[^'])+('|$) matches anything surrounded by two quote characters ('),
  30. // except a single quote symbol, which ends the sequence.
  31. // Two quote characters do not end the sequence.
  32. // If there is no matching single quote
  33. // then the sequence will continue until the end of the string.
  34. // - . matches any single character unmatched by previous parts of the RegExps
  35. const formattingTokensRegExp =
  36. /[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g;
  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. const escapedStringRegExp = /^'([^]*?)'?$/;
  41. const doubleQuoteRegExp = /''/g;
  42. const unescapedLatinCharacterRegExp = /[a-zA-Z]/;
  43. /**
  44. * The {@link format} function options.
  45. */
  46. /**
  47. * @name format
  48. * @alias formatDate
  49. * @category Common Helpers
  50. * @summary Format the date.
  51. *
  52. * @description
  53. * Return the formatted date string in the given format. The result may vary by locale.
  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 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. * (see the last example)
  61. *
  62. * Format of the string is based on Unicode Technical Standard #35:
  63. * https://www.unicode.org/reports/tr35/tr35-dates.html#Date_Field_Symbol_Table
  64. * with a few additions (see note 7 below the table).
  65. *
  66. * Accepted patterns:
  67. * | Unit | Pattern | Result examples | Notes |
  68. * |---------------------------------|---------|-----------------------------------|-------|
  69. * | Era | G..GGG | AD, BC | |
  70. * | | GGGG | Anno Domini, Before Christ | 2 |
  71. * | | GGGGG | A, B | |
  72. * | Calendar year | y | 44, 1, 1900, 2017 | 5 |
  73. * | | yo | 44th, 1st, 0th, 17th | 5,7 |
  74. * | | yy | 44, 01, 00, 17 | 5 |
  75. * | | yyy | 044, 001, 1900, 2017 | 5 |
  76. * | | yyyy | 0044, 0001, 1900, 2017 | 5 |
  77. * | | yyyyy | ... | 3,5 |
  78. * | Local week-numbering year | Y | 44, 1, 1900, 2017 | 5 |
  79. * | | Yo | 44th, 1st, 1900th, 2017th | 5,7 |
  80. * | | YY | 44, 01, 00, 17 | 5,8 |
  81. * | | YYY | 044, 001, 1900, 2017 | 5 |
  82. * | | YYYY | 0044, 0001, 1900, 2017 | 5,8 |
  83. * | | YYYYY | ... | 3,5 |
  84. * | ISO week-numbering year | R | -43, 0, 1, 1900, 2017 | 5,7 |
  85. * | | RR | -43, 00, 01, 1900, 2017 | 5,7 |
  86. * | | RRR | -043, 000, 001, 1900, 2017 | 5,7 |
  87. * | | RRRR | -0043, 0000, 0001, 1900, 2017 | 5,7 |
  88. * | | RRRRR | ... | 3,5,7 |
  89. * | Extended year | u | -43, 0, 1, 1900, 2017 | 5 |
  90. * | | uu | -43, 01, 1900, 2017 | 5 |
  91. * | | uuu | -043, 001, 1900, 2017 | 5 |
  92. * | | uuuu | -0043, 0001, 1900, 2017 | 5 |
  93. * | | uuuuu | ... | 3,5 |
  94. * | Quarter (formatting) | Q | 1, 2, 3, 4 | |
  95. * | | Qo | 1st, 2nd, 3rd, 4th | 7 |
  96. * | | QQ | 01, 02, 03, 04 | |
  97. * | | QQQ | Q1, Q2, Q3, Q4 | |
  98. * | | QQQQ | 1st quarter, 2nd quarter, ... | 2 |
  99. * | | QQQQQ | 1, 2, 3, 4 | 4 |
  100. * | Quarter (stand-alone) | q | 1, 2, 3, 4 | |
  101. * | | qo | 1st, 2nd, 3rd, 4th | 7 |
  102. * | | qq | 01, 02, 03, 04 | |
  103. * | | qqq | Q1, Q2, Q3, Q4 | |
  104. * | | qqqq | 1st quarter, 2nd quarter, ... | 2 |
  105. * | | qqqqq | 1, 2, 3, 4 | 4 |
  106. * | Month (formatting) | M | 1, 2, ..., 12 | |
  107. * | | Mo | 1st, 2nd, ..., 12th | 7 |
  108. * | | MM | 01, 02, ..., 12 | |
  109. * | | MMM | Jan, Feb, ..., Dec | |
  110. * | | MMMM | January, February, ..., December | 2 |
  111. * | | MMMMM | J, F, ..., D | |
  112. * | Month (stand-alone) | L | 1, 2, ..., 12 | |
  113. * | | Lo | 1st, 2nd, ..., 12th | 7 |
  114. * | | LL | 01, 02, ..., 12 | |
  115. * | | LLL | Jan, Feb, ..., Dec | |
  116. * | | LLLL | January, February, ..., December | 2 |
  117. * | | LLLLL | J, F, ..., D | |
  118. * | Local week of year | w | 1, 2, ..., 53 | |
  119. * | | wo | 1st, 2nd, ..., 53th | 7 |
  120. * | | ww | 01, 02, ..., 53 | |
  121. * | ISO week of year | I | 1, 2, ..., 53 | 7 |
  122. * | | Io | 1st, 2nd, ..., 53th | 7 |
  123. * | | II | 01, 02, ..., 53 | 7 |
  124. * | Day of month | d | 1, 2, ..., 31 | |
  125. * | | do | 1st, 2nd, ..., 31st | 7 |
  126. * | | dd | 01, 02, ..., 31 | |
  127. * | Day of year | D | 1, 2, ..., 365, 366 | 9 |
  128. * | | Do | 1st, 2nd, ..., 365th, 366th | 7 |
  129. * | | DD | 01, 02, ..., 365, 366 | 9 |
  130. * | | DDD | 001, 002, ..., 365, 366 | |
  131. * | | DDDD | ... | 3 |
  132. * | Day of week (formatting) | E..EEE | Mon, Tue, Wed, ..., Sun | |
  133. * | | EEEE | Monday, Tuesday, ..., Sunday | 2 |
  134. * | | EEEEE | M, T, W, T, F, S, S | |
  135. * | | EEEEEE | Mo, Tu, We, Th, Fr, Sa, Su | |
  136. * | ISO day of week (formatting) | i | 1, 2, 3, ..., 7 | 7 |
  137. * | | io | 1st, 2nd, ..., 7th | 7 |
  138. * | | ii | 01, 02, ..., 07 | 7 |
  139. * | | iii | Mon, Tue, Wed, ..., Sun | 7 |
  140. * | | iiii | Monday, Tuesday, ..., Sunday | 2,7 |
  141. * | | iiiii | M, T, W, T, F, S, S | 7 |
  142. * | | iiiiii | Mo, Tu, We, Th, Fr, Sa, Su | 7 |
  143. * | Local day of week (formatting) | e | 2, 3, 4, ..., 1 | |
  144. * | | eo | 2nd, 3rd, ..., 1st | 7 |
  145. * | | ee | 02, 03, ..., 01 | |
  146. * | | eee | Mon, Tue, Wed, ..., Sun | |
  147. * | | eeee | Monday, Tuesday, ..., Sunday | 2 |
  148. * | | eeeee | M, T, W, T, F, S, S | |
  149. * | | eeeeee | Mo, Tu, We, Th, Fr, Sa, Su | |
  150. * | Local day of week (stand-alone) | c | 2, 3, 4, ..., 1 | |
  151. * | | co | 2nd, 3rd, ..., 1st | 7 |
  152. * | | cc | 02, 03, ..., 01 | |
  153. * | | ccc | Mon, Tue, Wed, ..., Sun | |
  154. * | | cccc | Monday, Tuesday, ..., Sunday | 2 |
  155. * | | ccccc | M, T, W, T, F, S, S | |
  156. * | | cccccc | Mo, Tu, We, Th, Fr, Sa, Su | |
  157. * | AM, PM | a..aa | AM, PM | |
  158. * | | aaa | am, pm | |
  159. * | | aaaa | a.m., p.m. | 2 |
  160. * | | aaaaa | a, p | |
  161. * | AM, PM, noon, midnight | b..bb | AM, PM, noon, midnight | |
  162. * | | bbb | am, pm, noon, midnight | |
  163. * | | bbbb | a.m., p.m., noon, midnight | 2 |
  164. * | | bbbbb | a, p, n, mi | |
  165. * | Flexible day period | B..BBB | at night, in the morning, ... | |
  166. * | | BBBB | at night, in the morning, ... | 2 |
  167. * | | BBBBB | at night, in the morning, ... | |
  168. * | Hour [1-12] | h | 1, 2, ..., 11, 12 | |
  169. * | | ho | 1st, 2nd, ..., 11th, 12th | 7 |
  170. * | | hh | 01, 02, ..., 11, 12 | |
  171. * | Hour [0-23] | H | 0, 1, 2, ..., 23 | |
  172. * | | Ho | 0th, 1st, 2nd, ..., 23rd | 7 |
  173. * | | HH | 00, 01, 02, ..., 23 | |
  174. * | Hour [0-11] | K | 1, 2, ..., 11, 0 | |
  175. * | | Ko | 1st, 2nd, ..., 11th, 0th | 7 |
  176. * | | KK | 01, 02, ..., 11, 00 | |
  177. * | Hour [1-24] | k | 24, 1, 2, ..., 23 | |
  178. * | | ko | 24th, 1st, 2nd, ..., 23rd | 7 |
  179. * | | kk | 24, 01, 02, ..., 23 | |
  180. * | Minute | m | 0, 1, ..., 59 | |
  181. * | | mo | 0th, 1st, ..., 59th | 7 |
  182. * | | mm | 00, 01, ..., 59 | |
  183. * | Second | s | 0, 1, ..., 59 | |
  184. * | | so | 0th, 1st, ..., 59th | 7 |
  185. * | | ss | 00, 01, ..., 59 | |
  186. * | Fraction of second | S | 0, 1, ..., 9 | |
  187. * | | SS | 00, 01, ..., 99 | |
  188. * | | SSS | 000, 001, ..., 999 | |
  189. * | | SSSS | ... | 3 |
  190. * | Timezone (ISO-8601 w/ Z) | X | -08, +0530, Z | |
  191. * | | XX | -0800, +0530, Z | |
  192. * | | XXX | -08:00, +05:30, Z | |
  193. * | | XXXX | -0800, +0530, Z, +123456 | 2 |
  194. * | | XXXXX | -08:00, +05:30, Z, +12:34:56 | |
  195. * | Timezone (ISO-8601 w/o Z) | x | -08, +0530, +00 | |
  196. * | | xx | -0800, +0530, +0000 | |
  197. * | | xxx | -08:00, +05:30, +00:00 | 2 |
  198. * | | xxxx | -0800, +0530, +0000, +123456 | |
  199. * | | xxxxx | -08:00, +05:30, +00:00, +12:34:56 | |
  200. * | Timezone (GMT) | O...OOO | GMT-8, GMT+5:30, GMT+0 | |
  201. * | | OOOO | GMT-08:00, GMT+05:30, GMT+00:00 | 2 |
  202. * | Timezone (specific non-locat.) | z...zzz | GMT-8, GMT+5:30, GMT+0 | 6 |
  203. * | | zzzz | GMT-08:00, GMT+05:30, GMT+00:00 | 2,6 |
  204. * | Seconds timestamp | t | 512969520 | 7 |
  205. * | | tt | ... | 3,7 |
  206. * | Milliseconds timestamp | T | 512969520900 | 7 |
  207. * | | TT | ... | 3,7 |
  208. * | Long localized date | P | 04/29/1453 | 7 |
  209. * | | PP | Apr 29, 1453 | 7 |
  210. * | | PPP | April 29th, 1453 | 7 |
  211. * | | PPPP | Friday, April 29th, 1453 | 2,7 |
  212. * | Long localized time | p | 12:00 AM | 7 |
  213. * | | pp | 12:00:00 AM | 7 |
  214. * | | ppp | 12:00:00 AM GMT+2 | 7 |
  215. * | | pppp | 12:00:00 AM GMT+02:00 | 2,7 |
  216. * | Combination of date and time | Pp | 04/29/1453, 12:00 AM | 7 |
  217. * | | PPpp | Apr 29, 1453, 12:00:00 AM | 7 |
  218. * | | PPPppp | April 29th, 1453 at ... | 7 |
  219. * | | PPPPpppp| Friday, April 29th, 1453 at ... | 2,7 |
  220. * Notes:
  221. * 1. "Formatting" units (e.g. formatting quarter) in the default en-US locale
  222. * are the same as "stand-alone" units, but are different in some languages.
  223. * "Formatting" units are declined according to the rules of the language
  224. * in the context of a date. "Stand-alone" units are always nominative singular:
  225. *
  226. * `format(new Date(2017, 10, 6), 'do LLLL', {locale: cs}) //=> '6. listopad'`
  227. *
  228. * `format(new Date(2017, 10, 6), 'do MMMM', {locale: cs}) //=> '6. listopadu'`
  229. *
  230. * 2. Any sequence of the identical letters is a pattern, unless it is escaped by
  231. * the single quote characters (see below).
  232. * If the sequence is longer than listed in table (e.g. `EEEEEEEEEEE`)
  233. * the output will be the same as default pattern for this unit, usually
  234. * the longest one (in case of ISO weekdays, `EEEE`). Default patterns for units
  235. * are marked with "2" in the last column of the table.
  236. *
  237. * `format(new Date(2017, 10, 6), 'MMM') //=> 'Nov'`
  238. *
  239. * `format(new Date(2017, 10, 6), 'MMMM') //=> 'November'`
  240. *
  241. * `format(new Date(2017, 10, 6), 'MMMMM') //=> 'N'`
  242. *
  243. * `format(new Date(2017, 10, 6), 'MMMMMM') //=> 'November'`
  244. *
  245. * `format(new Date(2017, 10, 6), 'MMMMMMM') //=> 'November'`
  246. *
  247. * 3. Some patterns could be unlimited length (such as `yyyyyyyy`).
  248. * The output will be padded with zeros to match the length of the pattern.
  249. *
  250. * `format(new Date(2017, 10, 6), 'yyyyyyyy') //=> '00002017'`
  251. *
  252. * 4. `QQQQQ` and `qqqqq` could be not strictly numerical in some locales.
  253. * These tokens represent the shortest form of the quarter.
  254. *
  255. * 5. The main difference between `y` and `u` patterns are B.C. years:
  256. *
  257. * | Year | `y` | `u` |
  258. * |------|-----|-----|
  259. * | AC 1 | 1 | 1 |
  260. * | BC 1 | 1 | 0 |
  261. * | BC 2 | 2 | -1 |
  262. *
  263. * Also `yy` always returns the last two digits of a year,
  264. * while `uu` pads single digit years to 2 characters and returns other years unchanged:
  265. *
  266. * | Year | `yy` | `uu` |
  267. * |------|------|------|
  268. * | 1 | 01 | 01 |
  269. * | 14 | 14 | 14 |
  270. * | 376 | 76 | 376 |
  271. * | 1453 | 53 | 1453 |
  272. *
  273. * The same difference is true for local and ISO week-numbering years (`Y` and `R`),
  274. * except local week-numbering years are dependent on `options.weekStartsOn`
  275. * and `options.firstWeekContainsDate` (compare [getISOWeekYear](https://date-fns.org/docs/getISOWeekYear)
  276. * and [getWeekYear](https://date-fns.org/docs/getWeekYear)).
  277. *
  278. * 6. Specific non-location timezones are currently unavailable in `date-fns`,
  279. * so right now these tokens fall back to GMT timezones.
  280. *
  281. * 7. These patterns are not in the Unicode Technical Standard #35:
  282. * - `i`: ISO day of week
  283. * - `I`: ISO week of year
  284. * - `R`: ISO week-numbering year
  285. * - `t`: seconds timestamp
  286. * - `T`: milliseconds timestamp
  287. * - `o`: ordinal number modifier
  288. * - `P`: long localized date
  289. * - `p`: long localized time
  290. *
  291. * 8. `YY` and `YYYY` tokens represent week-numbering years but they are often confused with years.
  292. * You should enable `options.useAdditionalWeekYearTokens` to use them. See: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md
  293. *
  294. * 9. `D` and `DD` tokens represent days of the year but they are often confused with days of the month.
  295. * You should enable `options.useAdditionalDayOfYearTokens` to use them. See: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md
  296. *
  297. * @param date - The original date
  298. * @param format - The string of tokens
  299. * @param options - An object with options
  300. *
  301. * @returns The formatted date string
  302. *
  303. * @throws `date` must not be Invalid Date
  304. * @throws `options.locale` must contain `localize` property
  305. * @throws `options.locale` must contain `formatLong` property
  306. * @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
  307. * @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
  308. * @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
  309. * @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
  310. * @throws format string contains an unescaped latin alphabet character
  311. *
  312. * @example
  313. * // Represent 11 February 2014 in middle-endian format:
  314. * const result = format(new Date(2014, 1, 11), 'MM/dd/yyyy')
  315. * //=> '02/11/2014'
  316. *
  317. * @example
  318. * // Represent 2 July 2014 in Esperanto:
  319. * import { eoLocale } from 'date-fns/locale/eo'
  320. * const result = format(new Date(2014, 6, 2), "do 'de' MMMM yyyy", {
  321. * locale: eoLocale
  322. * })
  323. * //=> '2-a de julio 2014'
  324. *
  325. * @example
  326. * // Escape string by single quote characters:
  327. * const result = format(new Date(2014, 6, 2, 15), "h 'o''clock'")
  328. * //=> "3 o'clock"
  329. */
  330. function format(date, formatStr, options) {
  331. const defaultOptions = (0, _index2.getDefaultOptions)();
  332. const locale =
  333. options?.locale ?? defaultOptions.locale ?? _index.defaultLocale;
  334. const firstWeekContainsDate =
  335. options?.firstWeekContainsDate ??
  336. options?.locale?.options?.firstWeekContainsDate ??
  337. defaultOptions.firstWeekContainsDate ??
  338. defaultOptions.locale?.options?.firstWeekContainsDate ??
  339. 1;
  340. const weekStartsOn =
  341. options?.weekStartsOn ??
  342. options?.locale?.options?.weekStartsOn ??
  343. defaultOptions.weekStartsOn ??
  344. defaultOptions.locale?.options?.weekStartsOn ??
  345. 0;
  346. const originalDate = (0, _index7.toDate)(date, options?.in);
  347. if (!(0, _index6.isValid)(originalDate)) {
  348. throw new RangeError("Invalid time value");
  349. }
  350. let parts = formatStr
  351. .match(longFormattingTokensRegExp)
  352. .map((substring) => {
  353. const firstCharacter = substring[0];
  354. if (firstCharacter === "p" || firstCharacter === "P") {
  355. const longFormatter = _index4.longFormatters[firstCharacter];
  356. return longFormatter(substring, locale.formatLong);
  357. }
  358. return substring;
  359. })
  360. .join("")
  361. .match(formattingTokensRegExp)
  362. .map((substring) => {
  363. // Replace two single quote characters with one single quote character
  364. if (substring === "''") {
  365. return { isToken: false, value: "'" };
  366. }
  367. const firstCharacter = substring[0];
  368. if (firstCharacter === "'") {
  369. return { isToken: false, value: cleanEscapedString(substring) };
  370. }
  371. if (_index3.formatters[firstCharacter]) {
  372. return { isToken: true, value: substring };
  373. }
  374. if (firstCharacter.match(unescapedLatinCharacterRegExp)) {
  375. throw new RangeError(
  376. "Format string contains an unescaped latin alphabet character `" +
  377. firstCharacter +
  378. "`",
  379. );
  380. }
  381. return { isToken: false, value: substring };
  382. });
  383. // invoke localize preprocessor (only for french locales at the moment)
  384. if (locale.localize.preprocessor) {
  385. parts = locale.localize.preprocessor(originalDate, parts);
  386. }
  387. const formatterOptions = {
  388. firstWeekContainsDate,
  389. weekStartsOn,
  390. locale,
  391. };
  392. return parts
  393. .map((part) => {
  394. if (!part.isToken) return part.value;
  395. const token = part.value;
  396. if (
  397. (!options?.useAdditionalWeekYearTokens &&
  398. (0, _index5.isProtectedWeekYearToken)(token)) ||
  399. (!options?.useAdditionalDayOfYearTokens &&
  400. (0, _index5.isProtectedDayOfYearToken)(token))
  401. ) {
  402. (0, _index5.warnOrThrowProtectedError)(token, formatStr, String(date));
  403. }
  404. const formatter = _index3.formatters[token[0]];
  405. return formatter(originalDate, token, locale.localize, formatterOptions);
  406. })
  407. .join("");
  408. }
  409. function cleanEscapedString(input) {
  410. const matched = input.match(escapedStringRegExp);
  411. if (!matched) {
  412. return input;
  413. }
  414. return matched[1].replace(doubleQuoteRegExp, "'");
  415. }