format.js 24 KB

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