UNPKG

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