summaryrefslogtreecommitdiff
path: root/date-fns/src/format
diff options
context:
space:
mode:
Diffstat (limited to 'date-fns/src/format')
-rw-r--r--date-fns/src/format/benchmark.js21
-rw-r--r--date-fns/src/format/index.d.ts4
-rw-r--r--date-fns/src/format/index.js471
-rw-r--r--date-fns/src/format/index.js.flow62
-rw-r--r--date-fns/src/format/test.js813
5 files changed, 1371 insertions, 0 deletions
diff --git a/date-fns/src/format/benchmark.js b/date-fns/src/format/benchmark.js
new file mode 100644
index 0000000..38a9f86
--- /dev/null
+++ b/date-fns/src/format/benchmark.js
@@ -0,0 +1,21 @@
+// @flow
+/* eslint-env mocha */
+/* global suite, benchmark */
+
+import format from '.'
+import moment from 'moment'
+
+suite('format', function () {
+ benchmark('date-fns', function () {
+ return format(this.date, 'dddd, MMMM Do YYYY, h:mm:ss a')
+ })
+
+ benchmark('Moment.js', function () {
+ return this.moment.format('dddd, MMMM Do YYYY, h:mm:ss a')
+ })
+}, {
+ setup: function () {
+ this.date = new Date()
+ this.moment = moment()
+ }
+})
diff --git a/date-fns/src/format/index.d.ts b/date-fns/src/format/index.d.ts
new file mode 100644
index 0000000..06d38ce
--- /dev/null
+++ b/date-fns/src/format/index.d.ts
@@ -0,0 +1,4 @@
+// This file is generated automatically by `scripts/build/typings.js`. Please, don't change it.
+
+import { format } from 'date-fns'
+export default format
diff --git a/date-fns/src/format/index.js b/date-fns/src/format/index.js
new file mode 100644
index 0000000..5a532ea
--- /dev/null
+++ b/date-fns/src/format/index.js
@@ -0,0 +1,471 @@
+import isValid from '../isValid/index'
+import defaultLocale from '../locale/en-US/index'
+import subMilliseconds from '../subMilliseconds/index'
+import toDate from '../toDate/index'
+import formatters from '../_lib/format/formatters/index'
+import longFormatters from '../_lib/format/longFormatters/index'
+import getTimezoneOffsetInMilliseconds from '../_lib/getTimezoneOffsetInMilliseconds/index'
+import {
+ isProtectedDayOfYearToken,
+ isProtectedWeekYearToken,
+ throwProtectedError
+} from '../_lib/protectedTokens/index'
+import toInteger from '../_lib/toInteger/index'
+import requiredArgs from '../_lib/requiredArgs/index'
+
+// This RegExp consists of three parts separated by `|`:
+// - [yYQqMLwIdDecihHKkms]o matches any available ordinal number token
+// (one of the certain letters followed by `o`)
+// - (\w)\1* matches any sequences of the same letter
+// - '' matches two quote characters in a row
+// - '(''|[^'])+('|$) matches anything surrounded by two quote characters ('),
+// except a single quote symbol, which ends the sequence.
+// Two quote characters do not end the sequence.
+// If there is no matching single quote
+// then the sequence will continue until the end of the string.
+// - . matches any single character unmatched by previous parts of the RegExps
+var formattingTokensRegExp = /[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g
+
+// This RegExp catches symbols escaped by quotes, and also
+// sequences of symbols P, p, and the combinations like `PPPPPPPppppp`
+var longFormattingTokensRegExp = /P+p+|P+|p+|''|'(''|[^'])+('|$)|./g
+
+var escapedStringRegExp = /^'([^]*?)'?$/
+var doubleQuoteRegExp = /''/g
+var unescapedLatinCharacterRegExp = /[a-zA-Z]/
+
+/**
+ * @name format
+ * @category Common Helpers
+ * @summary Format the date.
+ *
+ * @description
+ * Return the formatted date string in the given format. The result may vary by locale.
+ *
+ * > ⚠️ Please note that the `format` tokens differ from Moment.js and other libraries.
+ * > See: https://git.io/fxCyr
+ *
+ * The characters wrapped between two single quotes characters (') are escaped.
+ * Two single quotes in a row, whether inside or outside a quoted sequence, represent a 'real' single quote.
+ * (see the last example)
+ *
+ * Format of the string is based on Unicode Technical Standard #35:
+ * https://www.unicode.org/reports/tr35/tr35-dates.html#Date_Field_Symbol_Table
+ * with a few additions (see note 7 below the table).
+ *
+ * Accepted patterns:
+ * | Unit | Pattern | Result examples | Notes |
+ * |---------------------------------|---------|-----------------------------------|-------|
+ * | Era | G..GGG | AD, BC | |
+ * | | GGGG | Anno Domini, Before Christ | 2 |
+ * | | GGGGG | A, B | |
+ * | Calendar year | y | 44, 1, 1900, 2017 | 5 |
+ * | | yo | 44th, 1st, 0th, 17th | 5,7 |
+ * | | yy | 44, 01, 00, 17 | 5 |
+ * | | yyy | 044, 001, 1900, 2017 | 5 |
+ * | | yyyy | 0044, 0001, 1900, 2017 | 5 |
+ * | | yyyyy | ... | 3,5 |
+ * | Local week-numbering year | Y | 44, 1, 1900, 2017 | 5 |
+ * | | Yo | 44th, 1st, 1900th, 2017th | 5,7 |
+ * | | YY | 44, 01, 00, 17 | 5,8 |
+ * | | YYY | 044, 001, 1900, 2017 | 5 |
+ * | | YYYY | 0044, 0001, 1900, 2017 | 5,8 |
+ * | | YYYYY | ... | 3,5 |
+ * | ISO week-numbering year | R | -43, 0, 1, 1900, 2017 | 5,7 |
+ * | | RR | -43, 00, 01, 1900, 2017 | 5,7 |
+ * | | RRR | -043, 000, 001, 1900, 2017 | 5,7 |
+ * | | RRRR | -0043, 0000, 0001, 1900, 2017 | 5,7 |
+ * | | RRRRR | ... | 3,5,7 |
+ * | Extended year | u | -43, 0, 1, 1900, 2017 | 5 |
+ * | | uu | -43, 01, 1900, 2017 | 5 |
+ * | | uuu | -043, 001, 1900, 2017 | 5 |
+ * | | uuuu | -0043, 0001, 1900, 2017 | 5 |
+ * | | uuuuu | ... | 3,5 |
+ * | Quarter (formatting) | Q | 1, 2, 3, 4 | |
+ * | | Qo | 1st, 2nd, 3rd, 4th | 7 |
+ * | | QQ | 01, 02, 03, 04 | |
+ * | | QQQ | Q1, Q2, Q3, Q4 | |
+ * | | QQQQ | 1st quarter, 2nd quarter, ... | 2 |
+ * | | QQQQQ | 1, 2, 3, 4 | 4 |
+ * | Quarter (stand-alone) | q | 1, 2, 3, 4 | |
+ * | | qo | 1st, 2nd, 3rd, 4th | 7 |
+ * | | qq | 01, 02, 03, 04 | |
+ * | | qqq | Q1, Q2, Q3, Q4 | |
+ * | | qqqq | 1st quarter, 2nd quarter, ... | 2 |
+ * | | qqqqq | 1, 2, 3, 4 | 4 |
+ * | Month (formatting) | M | 1, 2, ..., 12 | |
+ * | | Mo | 1st, 2nd, ..., 12th | 7 |
+ * | | MM | 01, 02, ..., 12 | |
+ * | | MMM | Jan, Feb, ..., Dec | |
+ * | | MMMM | January, February, ..., December | 2 |
+ * | | MMMMM | J, F, ..., D | |
+ * | Month (stand-alone) | L | 1, 2, ..., 12 | |
+ * | | Lo | 1st, 2nd, ..., 12th | 7 |
+ * | | LL | 01, 02, ..., 12 | |
+ * | | LLL | Jan, Feb, ..., Dec | |
+ * | | LLLL | January, February, ..., December | 2 |
+ * | | LLLLL | J, F, ..., D | |
+ * | Local week of year | w | 1, 2, ..., 53 | |
+ * | | wo | 1st, 2nd, ..., 53th | 7 |
+ * | | ww | 01, 02, ..., 53 | |
+ * | ISO week of year | I | 1, 2, ..., 53 | 7 |
+ * | | Io | 1st, 2nd, ..., 53th | 7 |
+ * | | II | 01, 02, ..., 53 | 7 |
+ * | Day of month | d | 1, 2, ..., 31 | |
+ * | | do | 1st, 2nd, ..., 31st | 7 |
+ * | | dd | 01, 02, ..., 31 | |
+ * | Day of year | D | 1, 2, ..., 365, 366 | 9 |
+ * | | Do | 1st, 2nd, ..., 365th, 366th | 7 |
+ * | | DD | 01, 02, ..., 365, 366 | 9 |
+ * | | DDD | 001, 002, ..., 365, 366 | |
+ * | | DDDD | ... | 3 |
+ * | Day of week (formatting) | E..EEE | Mon, Tue, Wed, ..., Sun | |
+ * | | EEEE | Monday, Tuesday, ..., Sunday | 2 |
+ * | | EEEEE | M, T, W, T, F, S, S | |
+ * | | EEEEEE | Mo, Tu, We, Th, Fr, Su, Sa | |
+ * | ISO day of week (formatting) | i | 1, 2, 3, ..., 7 | 7 |
+ * | | io | 1st, 2nd, ..., 7th | 7 |
+ * | | ii | 01, 02, ..., 07 | 7 |
+ * | | iii | Mon, Tue, Wed, ..., Sun | 7 |
+ * | | iiii | Monday, Tuesday, ..., Sunday | 2,7 |
+ * | | iiiii | M, T, W, T, F, S, S | 7 |
+ * | | iiiiii | Mo, Tu, We, Th, Fr, Su, Sa | 7 |
+ * | Local day of week (formatting) | e | 2, 3, 4, ..., 1 | |
+ * | | eo | 2nd, 3rd, ..., 1st | 7 |
+ * | | ee | 02, 03, ..., 01 | |
+ * | | eee | Mon, Tue, Wed, ..., Sun | |
+ * | | eeee | Monday, Tuesday, ..., Sunday | 2 |
+ * | | eeeee | M, T, W, T, F, S, S | |
+ * | | eeeeee | Mo, Tu, We, Th, Fr, Su, Sa | |
+ * | Local day of week (stand-alone) | c | 2, 3, 4, ..., 1 | |
+ * | | co | 2nd, 3rd, ..., 1st | 7 |
+ * | | cc | 02, 03, ..., 01 | |
+ * | | ccc | Mon, Tue, Wed, ..., Sun | |
+ * | | cccc | Monday, Tuesday, ..., Sunday | 2 |
+ * | | ccccc | M, T, W, T, F, S, S | |
+ * | | cccccc | Mo, Tu, We, Th, Fr, Su, Sa | |
+ * | AM, PM | a..aa | AM, PM | |
+ * | | aaa | am, pm | |
+ * | | aaaa | a.m., p.m. | 2 |
+ * | | aaaaa | a, p | |
+ * | AM, PM, noon, midnight | b..bb | AM, PM, noon, midnight | |
+ * | | bbb | am, pm, noon, midnight | |
+ * | | bbbb | a.m., p.m., noon, midnight | 2 |
+ * | | bbbbb | a, p, n, mi | |
+ * | Flexible day period | B..BBB | at night, in the morning, ... | |
+ * | | BBBB | at night, in the morning, ... | 2 |
+ * | | BBBBB | at night, in the morning, ... | |
+ * | Hour [1-12] | h | 1, 2, ..., 11, 12 | |
+ * | | ho | 1st, 2nd, ..., 11th, 12th | 7 |
+ * | | hh | 01, 02, ..., 11, 12 | |
+ * | Hour [0-23] | H | 0, 1, 2, ..., 23 | |
+ * | | Ho | 0th, 1st, 2nd, ..., 23rd | 7 |
+ * | | HH | 00, 01, 02, ..., 23 | |
+ * | Hour [0-11] | K | 1, 2, ..., 11, 0 | |
+ * | | Ko | 1st, 2nd, ..., 11th, 0th | 7 |
+ * | | KK | 01, 02, ..., 11, 00 | |
+ * | Hour [1-24] | k | 24, 1, 2, ..., 23 | |
+ * | | ko | 24th, 1st, 2nd, ..., 23rd | 7 |
+ * | | kk | 24, 01, 02, ..., 23 | |
+ * | Minute | m | 0, 1, ..., 59 | |
+ * | | mo | 0th, 1st, ..., 59th | 7 |
+ * | | mm | 00, 01, ..., 59 | |
+ * | Second | s | 0, 1, ..., 59 | |
+ * | | so | 0th, 1st, ..., 59th | 7 |
+ * | | ss | 00, 01, ..., 59 | |
+ * | Fraction of second | S | 0, 1, ..., 9 | |
+ * | | SS | 00, 01, ..., 99 | |
+ * | | SSS | 000, 001, ..., 999 | |
+ * | | SSSS | ... | 3 |
+ * | Timezone (ISO-8601 w/ Z) | X | -08, +0530, Z | |
+ * | | XX | -0800, +0530, Z | |
+ * | | XXX | -08:00, +05:30, Z | |
+ * | | XXXX | -0800, +0530, Z, +123456 | 2 |
+ * | | XXXXX | -08:00, +05:30, Z, +12:34:56 | |
+ * | Timezone (ISO-8601 w/o Z) | x | -08, +0530, +00 | |
+ * | | xx | -0800, +0530, +0000 | |
+ * | | xxx | -08:00, +05:30, +00:00 | 2 |
+ * | | xxxx | -0800, +0530, +0000, +123456 | |
+ * | | xxxxx | -08:00, +05:30, +00:00, +12:34:56 | |
+ * | Timezone (GMT) | O...OOO | GMT-8, GMT+5:30, GMT+0 | |
+ * | | OOOO | GMT-08:00, GMT+05:30, GMT+00:00 | 2 |
+ * | Timezone (specific non-locat.) | z...zzz | GMT-8, GMT+5:30, GMT+0 | 6 |
+ * | | zzzz | GMT-08:00, GMT+05:30, GMT+00:00 | 2,6 |
+ * | Seconds timestamp | t | 512969520 | 7 |
+ * | | tt | ... | 3,7 |
+ * | Milliseconds timestamp | T | 512969520900 | 7 |
+ * | | TT | ... | 3,7 |
+ * | Long localized date | P | 04/29/1453 | 7 |
+ * | | PP | Apr 29, 1453 | 7 |
+ * | | PPP | April 29th, 1453 | 7 |
+ * | | PPPP | Friday, April 29th, 1453 | 2,7 |
+ * | Long localized time | p | 12:00 AM | 7 |
+ * | | pp | 12:00:00 AM | 7 |
+ * | | ppp | 12:00:00 AM GMT+2 | 7 |
+ * | | pppp | 12:00:00 AM GMT+02:00 | 2,7 |
+ * | Combination of date and time | Pp | 04/29/1453, 12:00 AM | 7 |
+ * | | PPpp | Apr 29, 1453, 12:00:00 AM | 7 |
+ * | | PPPppp | April 29th, 1453 at ... | 7 |
+ * | | PPPPpppp| Friday, April 29th, 1453 at ... | 2,7 |
+ * Notes:
+ * 1. "Formatting" units (e.g. formatting quarter) in the default en-US locale
+ * are the same as "stand-alone" units, but are different in some languages.
+ * "Formatting" units are declined according to the rules of the language
+ * in the context of a date. "Stand-alone" units are always nominative singular:
+ *
+ * `format(new Date(2017, 10, 6), 'do LLLL', {locale: cs}) //=> '6. listopad'`
+ *
+ * `format(new Date(2017, 10, 6), 'do MMMM', {locale: cs}) //=> '6. listopadu'`
+ *
+ * 2. Any sequence of the identical letters is a pattern, unless it is escaped by
+ * the single quote characters (see below).
+ * If the sequence is longer than listed in table (e.g. `EEEEEEEEEEE`)
+ * the output will be the same as default pattern for this unit, usually
+ * the longest one (in case of ISO weekdays, `EEEE`). Default patterns for units
+ * are marked with "2" in the last column of the table.
+ *
+ * `format(new Date(2017, 10, 6), 'MMM') //=> 'Nov'`
+ *
+ * `format(new Date(2017, 10, 6), 'MMMM') //=> 'November'`
+ *
+ * `format(new Date(2017, 10, 6), 'MMMMM') //=> 'N'`
+ *
+ * `format(new Date(2017, 10, 6), 'MMMMMM') //=> 'November'`
+ *
+ * `format(new Date(2017, 10, 6), 'MMMMMMM') //=> 'November'`
+ *
+ * 3. Some patterns could be unlimited length (such as `yyyyyyyy`).
+ * The output will be padded with zeros to match the length of the pattern.
+ *
+ * `format(new Date(2017, 10, 6), 'yyyyyyyy') //=> '00002017'`
+ *
+ * 4. `QQQQQ` and `qqqqq` could be not strictly numerical in some locales.
+ * These tokens represent the shortest form of the quarter.
+ *
+ * 5. The main difference between `y` and `u` patterns are B.C. years:
+ *
+ * | Year | `y` | `u` |
+ * |------|-----|-----|
+ * | AC 1 | 1 | 1 |
+ * | BC 1 | 1 | 0 |
+ * | BC 2 | 2 | -1 |
+ *
+ * Also `yy` always returns the last two digits of a year,
+ * while `uu` pads single digit years to 2 characters and returns other years unchanged:
+ *
+ * | Year | `yy` | `uu` |
+ * |------|------|------|
+ * | 1 | 01 | 01 |
+ * | 14 | 14 | 14 |
+ * | 376 | 76 | 376 |
+ * | 1453 | 53 | 1453 |
+ *
+ * The same difference is true for local and ISO week-numbering years (`Y` and `R`),
+ * except local week-numbering years are dependent on `options.weekStartsOn`
+ * and `options.firstWeekContainsDate` (compare [getISOWeekYear]{@link https://date-fns.org/docs/getISOWeekYear}
+ * and [getWeekYear]{@link https://date-fns.org/docs/getWeekYear}).
+ *
+ * 6. Specific non-location timezones are currently unavailable in `date-fns`,
+ * so right now these tokens fall back to GMT timezones.
+ *
+ * 7. These patterns are not in the Unicode Technical Standard #35:
+ * - `i`: ISO day of week
+ * - `I`: ISO week of year
+ * - `R`: ISO week-numbering year
+ * - `t`: seconds timestamp
+ * - `T`: milliseconds timestamp
+ * - `o`: ordinal number modifier
+ * - `P`: long localized date
+ * - `p`: long localized time
+ *
+ * 8. `YY` and `YYYY` tokens represent week-numbering years but they are often confused with years.
+ * You should enable `options.useAdditionalWeekYearTokens` to use them. See: https://git.io/fxCyr
+ *
+ * 9. `D` and `DD` tokens represent days of the year but they are ofthen confused with days of the month.
+ * You should enable `options.useAdditionalDayOfYearTokens` to use them. See: https://git.io/fxCyr
+ *
+ * ### v2.0.0 breaking changes:
+ *
+ * - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
+ *
+ * - The second argument is now required for the sake of explicitness.
+ *
+ * ```javascript
+ * // Before v2.0.0
+ * format(new Date(2016, 0, 1))
+ *
+ * // v2.0.0 onward
+ * format(new Date(2016, 0, 1), "yyyy-MM-dd'T'HH:mm:ss.SSSxxx")
+ * ```
+ *
+ * - New format string API for `format` function
+ * which is based on [Unicode Technical Standard #35](https://www.unicode.org/reports/tr35/tr35-dates.html#Date_Field_Symbol_Table).
+ * See [this post](https://blog.date-fns.org/post/unicode-tokens-in-date-fns-v2-sreatyki91jg) for more details.
+ *
+ * - Characters are now escaped using single quote symbols (`'`) instead of square brackets.
+ *
+ * @param {Date|Number} date - the original date
+ * @param {String} format - the string of tokens
+ * @param {Object} [options] - an object with options.
+ * @param {Locale} [options.locale=defaultLocale] - the locale object. See [Locale]{@link https://date-fns.org/docs/Locale}
+ * @param {0|1|2|3|4|5|6} [options.weekStartsOn=0] - the index of the first day of the week (0 - Sunday)
+ * @param {Number} [options.firstWeekContainsDate=1] - the day of January, which is
+ * @param {Boolean} [options.useAdditionalWeekYearTokens=false] - if true, allows usage of the week-numbering year tokens `YY` and `YYYY`;
+ * see: https://git.io/fxCyr
+ * @param {Boolean} [options.useAdditionalDayOfYearTokens=false] - if true, allows usage of the day of year tokens `D` and `DD`;
+ * see: https://git.io/fxCyr
+ * @returns {String} the formatted date string
+ * @throws {TypeError} 2 arguments required
+ * @throws {RangeError} `date` must not be Invalid Date
+ * @throws {RangeError} `options.locale` must contain `localize` property
+ * @throws {RangeError} `options.locale` must contain `formatLong` property
+ * @throws {RangeError} `options.weekStartsOn` must be between 0 and 6
+ * @throws {RangeError} `options.firstWeekContainsDate` must be between 1 and 7
+ * @throws {RangeError} use `yyyy` instead of `YYYY` for formatting years using [format provided] to the input [input provided]; see: https://git.io/fxCyr
+ * @throws {RangeError} use `yy` instead of `YY` for formatting years using [format provided] to the input [input provided]; see: https://git.io/fxCyr
+ * @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
+ * @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
+ * @throws {RangeError} format string contains an unescaped latin alphabet character
+ *
+ * @example
+ * // Represent 11 February 2014 in middle-endian format:
+ * var result = format(new Date(2014, 1, 11), 'MM/dd/yyyy')
+ * //=> '02/11/2014'
+ *
+ * @example
+ * // Represent 2 July 2014 in Esperanto:
+ * import { eoLocale } from 'date-fns/locale/eo'
+ * var result = format(new Date(2014, 6, 2), "do 'de' MMMM yyyy", {
+ * locale: eoLocale
+ * })
+ * //=> '2-a de julio 2014'
+ *
+ * @example
+ * // Escape string by single quote characters:
+ * var result = format(new Date(2014, 6, 2, 15), "h 'o''clock'")
+ * //=> "3 o'clock"
+ */
+export default function format(dirtyDate, dirtyFormatStr, dirtyOptions) {
+ requiredArgs(2, arguments)
+
+ var formatStr = String(dirtyFormatStr)
+ var options = dirtyOptions || {}
+
+ var locale = options.locale || defaultLocale
+
+ var localeFirstWeekContainsDate =
+ locale.options && locale.options.firstWeekContainsDate
+ var defaultFirstWeekContainsDate =
+ localeFirstWeekContainsDate == null
+ ? 1
+ : toInteger(localeFirstWeekContainsDate)
+ var firstWeekContainsDate =
+ options.firstWeekContainsDate == null
+ ? defaultFirstWeekContainsDate
+ : toInteger(options.firstWeekContainsDate)
+
+ // Test if weekStartsOn is between 1 and 7 _and_ is not NaN
+ if (!(firstWeekContainsDate >= 1 && firstWeekContainsDate <= 7)) {
+ throw new RangeError(
+ 'firstWeekContainsDate must be between 1 and 7 inclusively'
+ )
+ }
+
+ var localeWeekStartsOn = locale.options && locale.options.weekStartsOn
+ var defaultWeekStartsOn =
+ localeWeekStartsOn == null ? 0 : toInteger(localeWeekStartsOn)
+ var weekStartsOn =
+ options.weekStartsOn == null
+ ? defaultWeekStartsOn
+ : toInteger(options.weekStartsOn)
+
+ // Test if weekStartsOn is between 0 and 6 _and_ is not NaN
+ if (!(weekStartsOn >= 0 && weekStartsOn <= 6)) {
+ throw new RangeError('weekStartsOn must be between 0 and 6 inclusively')
+ }
+
+ if (!locale.localize) {
+ throw new RangeError('locale must contain localize property')
+ }
+
+ if (!locale.formatLong) {
+ throw new RangeError('locale must contain formatLong property')
+ }
+
+ var originalDate = toDate(dirtyDate)
+
+ if (!isValid(originalDate)) {
+ throw new RangeError('Invalid time value')
+ }
+
+ // Convert the date in system timezone to the same date in UTC+00:00 timezone.
+ // This ensures that when UTC functions will be implemented, locales will be compatible with them.
+ // See an issue about UTC functions: https://github.com/date-fns/date-fns/issues/376
+ var timezoneOffset = getTimezoneOffsetInMilliseconds(originalDate)
+ var utcDate = subMilliseconds(originalDate, timezoneOffset)
+
+ var formatterOptions = {
+ firstWeekContainsDate: firstWeekContainsDate,
+ weekStartsOn: weekStartsOn,
+ locale: locale,
+ _originalDate: originalDate
+ }
+
+ var result = formatStr
+ .match(longFormattingTokensRegExp)
+ .map(function(substring) {
+ var firstCharacter = substring[0]
+ if (firstCharacter === 'p' || firstCharacter === 'P') {
+ var longFormatter = longFormatters[firstCharacter]
+ return longFormatter(substring, locale.formatLong, formatterOptions)
+ }
+ return substring
+ })
+ .join('')
+ .match(formattingTokensRegExp)
+ .map(function(substring) {
+ // Replace two single quote characters with one single quote character
+ if (substring === "''") {
+ return "'"
+ }
+
+ var firstCharacter = substring[0]
+ if (firstCharacter === "'") {
+ return cleanEscapedString(substring)
+ }
+
+ var formatter = formatters[firstCharacter]
+ if (formatter) {
+ if (
+ !options.useAdditionalWeekYearTokens &&
+ isProtectedWeekYearToken(substring)
+ ) {
+ throwProtectedError(substring, dirtyFormatStr, dirtyDate)
+ }
+ if (
+ !options.useAdditionalDayOfYearTokens &&
+ isProtectedDayOfYearToken(substring)
+ ) {
+ throwProtectedError(substring, dirtyFormatStr, dirtyDate)
+ }
+ return formatter(utcDate, substring, locale.localize, formatterOptions)
+ }
+
+ if (firstCharacter.match(unescapedLatinCharacterRegExp)) {
+ throw new RangeError(
+ 'Format string contains an unescaped latin alphabet character `' +
+ firstCharacter +
+ '`'
+ )
+ }
+
+ return substring
+ })
+ .join('')
+
+ return result
+}
+
+function cleanEscapedString(input) {
+ return input.match(escapedStringRegExp)[1].replace(doubleQuoteRegExp, "'")
+}
diff --git a/date-fns/src/format/index.js.flow b/date-fns/src/format/index.js.flow
new file mode 100644
index 0000000..ca79393
--- /dev/null
+++ b/date-fns/src/format/index.js.flow
@@ -0,0 +1,62 @@
+// @flow
+// This file is generated automatically by `scripts/build/typings.js`. Please, don't change it.
+
+export type Interval = {
+ start: Date | number,
+ end: Date | number,
+}
+
+export type Locale = {
+ code?: string,
+ formatDistance?: (...args: Array<any>) => any,
+ formatRelative?: (...args: Array<any>) => any,
+ localize?: {
+ ordinalNumber: (...args: Array<any>) => any,
+ era: (...args: Array<any>) => any,
+ quarter: (...args: Array<any>) => any,
+ month: (...args: Array<any>) => any,
+ day: (...args: Array<any>) => any,
+ dayPeriod: (...args: Array<any>) => any,
+ },
+ formatLong?: {
+ date: (...args: Array<any>) => any,
+ time: (...args: Array<any>) => any,
+ dateTime: (...args: Array<any>) => any,
+ },
+ match?: {
+ ordinalNumber: (...args: Array<any>) => any,
+ era: (...args: Array<any>) => any,
+ quarter: (...args: Array<any>) => any,
+ month: (...args: Array<any>) => any,
+ day: (...args: Array<any>) => any,
+ dayPeriod: (...args: Array<any>) => any,
+ },
+ options?: {
+ weekStartsOn?: 0 | 1 | 2 | 3 | 4 | 5 | 6,
+ firstWeekContainsDate?: 1 | 2 | 3 | 4 | 5 | 6 | 7,
+ },
+}
+
+export type Duration = {
+ years?: number,
+ months?: number,
+ weeks?: number,
+ days?: number,
+ hours?: number,
+ minutes?: number,
+ seconds?: number,
+}
+
+export type Day = 0 | 1 | 2 | 3 | 4 | 5 | 6
+
+declare module.exports: (
+ date: Date | number,
+ format: string,
+ options?: {
+ locale?: Locale,
+ weekStartsOn?: 0 | 1 | 2 | 3 | 4 | 5 | 6,
+ firstWeekContainsDate?: number,
+ useAdditionalWeekYearTokens?: boolean,
+ useAdditionalDayOfYearTokens?: boolean,
+ }
+) => string
diff --git a/date-fns/src/format/test.js b/date-fns/src/format/test.js
new file mode 100644
index 0000000..97ad003
--- /dev/null
+++ b/date-fns/src/format/test.js
@@ -0,0 +1,813 @@
+// @flow
+/* eslint-env mocha */
+
+import assert from 'power-assert'
+import format from '.'
+
+describe('format', function () {
+ var date = new Date(1986, 3 /* Apr */, 4, 10, 32, 55, 123)
+
+ var offset = date.getTimezoneOffset()
+ var absoluteOffset = Math.abs(offset)
+ var hours = Math.floor(absoluteOffset / 60)
+ var hoursLeadingZero = hours < 10 ? '0' : ''
+ var minutes = absoluteOffset % 60
+ var minutesLeadingZero = minutes < 10 ? '0' : ''
+ var sign = offset > 0 ? '-' : '+'
+
+ var timezone =
+ sign + hoursLeadingZero + hours + ':' + minutesLeadingZero + minutes
+ var timezoneShort = timezone.replace(':', '')
+ var timezoneWithOptionalMinutesShort =
+ minutes === 0 ? sign + hoursLeadingZero + hours : timezoneShort
+
+ var timezoneWithZ = offset === 0 ? 'Z' : timezone
+ var timezoneWithZShort = offset === 0 ? 'Z' : timezoneShort
+ var timezoneWithOptionalMinutesAndZShort =
+ offset === 0 ? 'Z' : timezoneWithOptionalMinutesShort
+
+ var timezoneGMTShort =
+ minutes === 0
+ ? 'GMT' + sign + hours
+ : 'GMT' + sign + hours + ':' + minutesLeadingZero + minutes
+ var timezoneGMT = 'GMT' + timezone
+
+ var timestamp = date.getTime().toString()
+ var secondsTimestamp = Math.floor(date.getTime() / 1000).toString()
+
+ it('accepts a timestamp', function () {
+ var date = new Date(2014, 3, 4).getTime()
+ assert(format(date, 'yyyy-MM-dd') === '2014-04-04')
+ })
+
+ it('escapes characters between the single quote characters', function () {
+ var result = format(date, "'yyyy-'MM-dd'THH:mm:ss.SSSX' yyyy-'MM-dd'")
+ assert(result === 'yyyy-04-04THH:mm:ss.SSSX 1986-MM-dd')
+ })
+
+ it('two single quote characters are transformed into a "real" single quote', function () {
+ var date = new Date(2014, 3, 4, 5)
+ assert(format(date, "''h 'o''clock'''") === "'5 o'clock'")
+ })
+
+ it('accepts new line charactor', function () {
+ var date = new Date(2014, 3, 4, 5)
+ assert.equal(format(date, "yyyy-MM-dd'\n'HH:mm:ss"), '2014-04-04\n05:00:00')
+ })
+
+ describe('ordinal numbers', function () {
+ it('ordinal day of an ordinal month', function () {
+ var result = format(date, "do 'day of the' Mo 'month of' yyyy")
+ assert(result === '4th day of the 4th month of 1986')
+ })
+
+ it('should return a correct ordinal number', function () {
+ var result = []
+ for (var i = 1; i <= 31; i++) {
+ result.push(format(new Date(2015, 0, i), 'do'))
+ }
+ var expected = [
+ '1st',
+ '2nd',
+ '3rd',
+ '4th',
+ '5th',
+ '6th',
+ '7th',
+ '8th',
+ '9th',
+ '10th',
+ '11th',
+ '12th',
+ '13th',
+ '14th',
+ '15th',
+ '16th',
+ '17th',
+ '18th',
+ '19th',
+ '20th',
+ '21st',
+ '22nd',
+ '23rd',
+ '24th',
+ '25th',
+ '26th',
+ '27th',
+ '28th',
+ '29th',
+ '30th',
+ '31st',
+ ]
+ assert.deepEqual(result, expected)
+ })
+ })
+
+ it('era', function () {
+ var result = format(date, 'G GG GGG GGGG GGGGG')
+ assert(result === 'AD AD AD Anno Domini A')
+ })
+
+ describe('year', function () {
+ describe('regular year', function () {
+ it('works as expected', function () {
+ var result = format(date, 'y yo yy yyy yyyy yyyyy')
+ assert(result === '1986 1986th 86 1986 1986 01986')
+ })
+
+ it('1 BC formats as 1', function () {
+ var date = new Date(0)
+ date.setFullYear(0, 0 /* Jan */, 1)
+ date.setHours(0, 0, 0, 0)
+ var result = format(date, 'y')
+ assert(result === '1')
+ })
+
+ it('2 BC formats as 2', function () {
+ var date = new Date(0)
+ date.setFullYear(-1, 0 /* Jan */, 1)
+ date.setHours(0, 0, 0, 0)
+ var result = format(date, 'y')
+ assert(result === '2')
+ })
+ })
+
+ describe('local week-numbering year', function () {
+ it('works as expected', function () {
+ var result = format(date, 'Y Yo YY YYY YYYY YYYYY', {
+ useAdditionalWeekYearTokens: true,
+ })
+ assert(result === '1986 1986th 86 1986 1986 01986')
+ })
+
+ it('the first week of the next year', function () {
+ var result = format(new Date(2013, 11 /* Dec */, 29), 'YYYY', {
+ useAdditionalWeekYearTokens: true,
+ })
+ assert(result === '2014')
+ })
+
+ it('allows to specify `weekStartsOn` and `firstWeekContainsDate` in options', function () {
+ var result = format(new Date(2013, 11 /* Dec */, 29), 'YYYY', {
+ weekStartsOn: 1,
+ firstWeekContainsDate: 4,
+ useAdditionalWeekYearTokens: true,
+ })
+ assert(result === '2013')
+ })
+
+ it('the first week of year', function () {
+ var result = format(new Date(2016, 0 /* Jan */, 1), 'YYYY', {
+ useAdditionalWeekYearTokens: true,
+ })
+ assert(result === '2016')
+ })
+
+ it('1 BC formats as 1', function () {
+ var date = new Date(0)
+ date.setFullYear(0, 6 /* Jul */, 2)
+ date.setHours(0, 0, 0, 0)
+ var result = format(date, 'Y')
+ assert(result === '1')
+ })
+
+ it('2 BC formats as 2', function () {
+ var date = new Date(0)
+ date.setFullYear(-1, 6 /* Jul */, 2)
+ date.setHours(0, 0, 0, 0)
+ var result = format(date, 'Y')
+ assert(result === '2')
+ })
+ })
+
+ describe('ISO week-numbering year', function () {
+ it('works as expected', function () {
+ var result = format(date, 'R RR RRR RRRR RRRRR')
+ assert(result === '1986 1986 1986 1986 01986')
+ })
+
+ it('the first week of the next year', function () {
+ var result = format(new Date(2013, 11 /* Dec */, 30), 'RRRR')
+ assert(result === '2014')
+ })
+
+ it('the last week of the previous year', function () {
+ var result = format(new Date(2016, 0 /* Jan */, 1), 'RRRR')
+ assert(result === '2015')
+ })
+
+ it('1 BC formats as 0', function () {
+ var date = new Date(0)
+ date.setFullYear(0, 6 /* Jul */, 2)
+ date.setHours(0, 0, 0, 0)
+ var result = format(date, 'R')
+ assert(result === '0')
+ })
+
+ it('2 BC formats as -1', function () {
+ var date = new Date(0)
+ date.setFullYear(-1, 6 /* Jul */, 2)
+ date.setHours(0, 0, 0, 0)
+ var result = format(date, 'R')
+ assert(result === '-1')
+ })
+ })
+
+ describe('extended year', function () {
+ it('works as expected', function () {
+ var result = format(date, 'u uu uuu uuuu uuuuu')
+ assert(result === '1986 1986 1986 1986 01986')
+ })
+
+ it('1 BC formats as 0', function () {
+ var date = new Date(0)
+ date.setFullYear(0, 0, 1)
+ date.setHours(0, 0, 0, 0)
+ var result = format(date, 'u')
+ assert(result === '0')
+ })
+
+ it('2 BC formats as -1', function () {
+ var date = new Date(0)
+ date.setFullYear(-1, 0, 1)
+ date.setHours(0, 0, 0, 0)
+ var result = format(date, 'u')
+ assert(result === '-1')
+ })
+ })
+ })
+
+ describe('quarter', function () {
+ it('formatting quarter', function () {
+ var result = format(date, 'Q Qo QQ QQQ QQQQ QQQQQ')
+ assert(result === '2 2nd 02 Q2 2nd quarter 2')
+ })
+
+ it('stand-alone quarter', function () {
+ var result = format(date, 'q qo qq qqq qqqq qqqqq')
+ assert(result === '2 2nd 02 Q2 2nd quarter 2')
+ })
+
+ it('returns a correct quarter for each month', function () {
+ var result = []
+ for (var i = 0; i <= 11; i++) {
+ result.push(format(new Date(1986, i, 1), 'Q'))
+ }
+ var expected = [
+ '1',
+ '1',
+ '1',
+ '2',
+ '2',
+ '2',
+ '3',
+ '3',
+ '3',
+ '4',
+ '4',
+ '4',
+ ]
+ assert.deepEqual(result, expected)
+ })
+ })
+
+ describe('month', function () {
+ it('formatting month', function () {
+ var result = format(date, 'M Mo MM MMM MMMM MMMMM')
+ assert(result === '4 4th 04 Apr April A')
+ })
+
+ it('stand-alone month', function () {
+ var result = format(date, 'L Lo LL LLL LLLL LLLLL')
+ assert(result === '4 4th 04 Apr April A')
+ })
+ })
+
+ describe('week', function () {
+ describe('local week of year', function () {
+ it('works as expected', function () {
+ var date = new Date(1986, 3 /* Apr */, 6)
+ var result = format(date, 'w wo ww')
+ assert(result === '15 15th 15')
+ })
+
+ it('allows to specify `weekStartsOn` and `firstWeekContainsDate` in options', function () {
+ var date = new Date(1986, 3 /* Apr */, 6)
+ var result = format(date, 'w wo ww', {
+ weekStartsOn: 1,
+ firstWeekContainsDate: 4,
+ })
+ assert(result === '14 14th 14')
+ })
+ })
+
+ it('ISO week of year', function () {
+ var date = new Date(1986, 3 /* Apr */, 6)
+ var result = format(date, 'I Io II')
+ assert(result === '14 14th 14')
+ })
+ })
+
+ describe('day', function () {
+ it('date', function () {
+ var result = format(date, 'd do dd')
+ assert(result === '4 4th 04')
+ })
+
+ describe('day of year', function () {
+ it('works as expected', function () {
+ var result = format(date, 'D Do DD DDD DDDDD', {
+ useAdditionalDayOfYearTokens: true,
+ })
+ assert(result === '94 94th 94 094 00094')
+ })
+
+ it('returns a correct day number for the last day of a leap year', function () {
+ var result = format(
+ new Date(1992, 11 /* Dec */, 31, 23, 59, 59, 999),
+ 'D',
+ { useAdditionalDayOfYearTokens: true }
+ )
+ assert(result === '366')
+ })
+ })
+ })
+
+ describe('week day', function () {
+ describe('day of week', function () {
+ it('works as expected', function () {
+ var result = format(date, 'E EE EEE EEEE EEEEE EEEEEE')
+ assert(result === 'Fri Fri Fri Friday F Fr')
+ })
+ })
+
+ describe('ISO day of week', function () {
+ it('works as expected', function () {
+ var result = format(date, 'i io ii iii iiii iiiii iiiiii')
+ assert(result === '5 5th 05 Fri Friday F Fr')
+ })
+
+ it('returns a correct day of an ISO week', function () {
+ var result = []
+ for (var i = 1; i <= 7; i++) {
+ result.push(format(new Date(1986, 8 /* Sep */, i), 'i'))
+ }
+ var expected = ['1', '2', '3', '4', '5', '6', '7']
+ assert.deepEqual(result, expected)
+ })
+ })
+
+ describe('formatting day of week', function () {
+ it('works as expected', function () {
+ var result = format(date, 'e eo ee eee eeee eeeee eeeeee')
+ assert(result === '6 6th 06 Fri Friday F Fr')
+ })
+
+ it('by default, 1 is Sunday, 2 is Monday, ...', function () {
+ var result = []
+ for (var i = 7; i <= 13; i++) {
+ result.push(format(new Date(1986, 8 /* Sep */, i), 'e'))
+ }
+ var expected = ['1', '2', '3', '4', '5', '6', '7']
+ assert.deepEqual(result, expected)
+ })
+
+ it('allows to specify which day is the first day of the week', function () {
+ var result = []
+ for (var i = 1; i <= 7; i++) {
+ result.push(
+ format(new Date(1986, 8 /* Sep */, i), 'e', { weekStartsOn: 1 })
+ )
+ }
+ var expected = ['1', '2', '3', '4', '5', '6', '7']
+ assert.deepEqual(result, expected)
+ })
+ })
+
+ describe('stand-alone day of week', function () {
+ it('works as expected', function () {
+ var result = format(date, 'c co cc ccc cccc ccccc cccccc')
+ assert(result === '6 6th 06 Fri Friday F Fr')
+ })
+
+ it('by default, 1 is Sunday, 2 is Monday, ...', function () {
+ var result = []
+ for (var i = 7; i <= 13; i++) {
+ result.push(format(new Date(1986, 8 /* Sep */, i), 'c'))
+ }
+ var expected = ['1', '2', '3', '4', '5', '6', '7']
+ assert.deepEqual(result, expected)
+ })
+
+ it('allows to specify which day is the first day of the week', function () {
+ var result = []
+ for (var i = 1; i <= 7; i++) {
+ result.push(
+ format(new Date(1986, 8 /* Sep */, i), 'c', { weekStartsOn: 1 })
+ )
+ }
+ var expected = ['1', '2', '3', '4', '5', '6', '7']
+ assert.deepEqual(result, expected)
+ })
+ })
+ })
+
+ describe('day period and hour', function () {
+ it('hour [1-12]', function () {
+ var result = format(new Date(2018, 0 /* Jan */, 1, 0, 0, 0, 0), 'h ho hh')
+ assert(result === '12 12th 12')
+ })
+
+ it('hour [0-23]', function () {
+ var result = format(new Date(2018, 0 /* Jan */, 1, 0, 0, 0, 0), 'H Ho HH')
+ assert(result === '0 0th 00')
+ })
+
+ it('hour [0-11]', function () {
+ var result = format(new Date(2018, 0 /* Jan */, 1, 0, 0, 0, 0), 'K Ko KK')
+ assert(result === '0 0th 00')
+ })
+
+ it('hour [1-24]', function () {
+ var result = format(new Date(2018, 0 /* Jan */, 1, 0, 0, 0, 0), 'k ko kk')
+ assert(result === '24 24th 24')
+ })
+
+ describe('AM, PM', function () {
+ it('works as expected', function () {
+ var result = format(
+ new Date(2018, 0 /* Jan */, 1, 0, 0, 0, 0),
+ 'a aa aaa aaaa aaaaa'
+ )
+ assert(result === 'AM AM am a.m. a')
+ })
+
+ it('12 PM', function () {
+ var date = new Date(1986, 3 /* Apr */, 4, 12, 0, 0, 900)
+ assert(format(date, 'h H K k a') === '12 12 0 12 PM')
+ })
+
+ it('12 AM', function () {
+ var date = new Date(1986, 3 /* Apr */, 6, 0, 0, 0, 900)
+ assert(format(date, 'h H K k a') === '12 0 0 24 AM')
+ })
+ })
+
+ describe('AM, PM, noon, midnight', function () {
+ it('works as expected', function () {
+ var result = format(
+ new Date(1986, 3 /* Apr */, 6, 2, 0, 0, 900),
+ 'b bb bbb bbbb bbbbb'
+ )
+ assert(result === 'AM AM am a.m. a')
+ })
+
+ it('12 PM', function () {
+ var date = new Date(1986, 3 /* Apr */, 4, 12, 0, 0, 900)
+ assert(format(date, 'b bb bbb bbbb bbbbb') === 'noon noon noon noon n')
+ })
+
+ it('12 AM', function () {
+ var date = new Date(1986, 3 /* Apr */, 6, 0, 0, 0, 900)
+ assert(
+ format(date, 'b bb bbb bbbb bbbbb') ===
+ 'midnight midnight midnight midnight mi'
+ )
+ })
+ })
+
+ describe('flexible day periods', function () {
+ it('works as expected', function () {
+ var result = format(date, 'B, BB, BBB, BBBB, BBBBB')
+ assert(
+ result ===
+ 'in the morning, in the morning, in the morning, in the morning, in the morning'
+ )
+ })
+
+ it('12 PM', function () {
+ var date = new Date(1986, 3 /* Apr */, 4, 12, 0, 0, 900)
+ assert(format(date, 'h B') === '12 in the afternoon')
+ })
+
+ it('5 PM', function () {
+ var date = new Date(1986, 3 /* Apr */, 6, 17, 0, 0, 900)
+ assert(format(date, 'h B') === '5 in the evening')
+ })
+
+ it('12 AM', function () {
+ var date = new Date(1986, 3 /* Apr */, 6, 0, 0, 0, 900)
+ assert(format(date, 'h B') === '12 at night')
+ })
+
+ it('4 AM', function () {
+ var date = new Date(1986, 3 /* Apr */, 6, 4, 0, 0, 900)
+ assert(format(date, 'h B') === '4 in the morning')
+ })
+ })
+ })
+
+ it('minute', function () {
+ var result = format(date, 'm mo mm')
+ assert(result === '32 32nd 32')
+ })
+
+ describe('second', function () {
+ it('second', function () {
+ var result = format(date, 's so ss')
+ assert(result === '55 55th 55')
+ })
+
+ it('fractional seconds', function () {
+ var result = format(date, 'S SS SSS SSSS')
+ assert(result === '1 12 123 1230')
+ })
+ })
+
+ describe('time zone', function () {
+ it('ISO-8601 with Z', function () {
+ var result = format(date, 'X XX XXX XXXX XXXXX')
+ var expectedResult = [
+ timezoneWithOptionalMinutesAndZShort,
+ timezoneWithZShort,
+ timezoneWithZ,
+ timezoneWithZShort,
+ timezoneWithZ,
+ ].join(' ')
+ assert(result === expectedResult)
+ })
+
+ it('ISO-8601 without Z', function () {
+ var result = format(date, 'x xx xxx xxxx xxxxx')
+ var expectedResult = [
+ timezoneWithOptionalMinutesShort,
+ timezoneShort,
+ timezone,
+ timezoneShort,
+ timezone,
+ ].join(' ')
+ assert(result === expectedResult)
+ })
+
+ it('GMT', function () {
+ var result = format(date, 'O OO OOO OOOO')
+ var expectedResult = [
+ timezoneGMTShort,
+ timezoneGMTShort,
+ timezoneGMTShort,
+ timezoneGMT,
+ ].join(' ')
+ assert(result === expectedResult)
+ })
+
+ it('Specific non-location', function () {
+ var result = format(date, 'z zz zzz zzzz')
+ var expectedResult = [
+ timezoneGMTShort,
+ timezoneGMTShort,
+ timezoneGMTShort,
+ timezoneGMT,
+ ].join(' ')
+ assert(result === expectedResult)
+ })
+ })
+
+ describe('timestamp', function () {
+ it('seconds timestamp', function () {
+ var result = format(date, 't')
+ assert(result === secondsTimestamp)
+ })
+
+ it('milliseconds timestamp', function () {
+ var result = format(date, 'T')
+ assert(result === timestamp)
+ })
+ })
+
+ describe('long format', function () {
+ it('short date', function () {
+ var result = format(date, 'P')
+ assert(result === '04/04/1986')
+ })
+
+ it('medium date', function () {
+ var result = format(date, 'PP')
+ assert(result === 'Apr 4, 1986')
+ })
+
+ it('long date', function () {
+ var result = format(date, 'PPP')
+ assert(result === 'April 4th, 1986')
+ })
+
+ it('full date', function () {
+ var result = format(date, 'PPPP')
+ assert(result === 'Friday, April 4th, 1986')
+ })
+
+ it('short time', function () {
+ var result = format(date, 'p')
+ assert(result === '10:32 AM')
+ })
+
+ it('medium time', function () {
+ var result = format(date, 'pp')
+ assert(result === '10:32:55 AM')
+ })
+
+ it('long time', function () {
+ var result = format(date, 'ppp')
+ assert(result === '10:32:55 AM ' + timezoneGMTShort)
+ })
+
+ it('full time', function () {
+ var result = format(date, 'pppp')
+ assert(result === '10:32:55 AM ' + timezoneGMT)
+ })
+
+ it('short date + time', function () {
+ var result = format(date, 'Pp')
+ assert(result === '04/04/1986, 10:32 AM')
+ })
+
+ it('medium date + time', function () {
+ var result = format(date, 'PPpp')
+ assert(result === 'Apr 4, 1986, 10:32:55 AM')
+ })
+
+ it('long date + time', function () {
+ var result = format(date, 'PPPppp')
+ assert(result === 'April 4th, 1986 at 10:32:55 AM ' + timezoneGMTShort)
+ })
+
+ it('full date + time', function () {
+ var result = format(date, 'PPPPpppp')
+ assert(result === 'Friday, April 4th, 1986 at 10:32:55 AM ' + timezoneGMT)
+ })
+
+ it('allows arbitrary combination of date and time', function () {
+ var result = format(date, 'Ppppp')
+ assert(result === '04/04/1986, 10:32:55 AM ' + timezoneGMT)
+ })
+ })
+
+ describe('edge cases', function () {
+ it('throws RangeError if the time value is invalid', () => {
+ assert.throws(
+ format.bind(null, new Date(NaN), 'MMMM d, yyyy'),
+ RangeError
+ )
+ })
+
+ it('handles dates before 100 AD', function () {
+ var initialDate = new Date(0)
+ initialDate.setFullYear(7, 11 /* Dec */, 31)
+ initialDate.setHours(0, 0, 0, 0)
+ assert(format(initialDate, 'Y ww i') === '8 01 1')
+ })
+ })
+
+ it('implicitly converts `formatString`', function () {
+ // eslint-disable-next-line no-new-wrappers
+ var formatString = new String('yyyy-MM-dd')
+
+ var date = new Date(2014, 3, 4)
+
+ // $ExpectedMistake
+ assert(format(date, formatString) === '2014-04-04')
+ })
+
+ describe('custom locale', function () {
+ it('allows to pass a custom locale', function () {
+ var customLocale = {
+ localize: {
+ month: function () {
+ return 'works'
+ },
+ },
+ formatLong: {
+ date: function () {
+ return "'It' MMMM!"
+ },
+ },
+ }
+ // $ExpectedMistake
+ var result = format(date, 'PPPP', { locale: customLocale })
+ assert(result === 'It works!')
+ })
+
+ it("throws `RangeError` if `options.locale` doesn't have `localize` property", function () {
+ var customLocale = {
+ formatLong: {},
+ }
+ // $ExpectedMistake
+ var block = format.bind(null, date, 'yyyy-MM-dd', {
+ locale: customLocale,
+ })
+ assert.throws(block, RangeError)
+ })
+
+ it("throws `RangeError` if `options.locale` doesn't have `formatLong` property", function () {
+ var customLocale = {
+ // $ExpectedMistake
+ localize: {},
+ }
+ // $ExpectedMistake
+ var block = format.bind(null, date, 'yyyy-MM-dd', {
+ locale: customLocale,
+ })
+ assert.throws(block, RangeError)
+ })
+ })
+
+ it('throws `RangeError` if `options.weekStartsOn` is not convertable to 0, 1, ..., 6 or undefined', function () {
+ // $ExpectedMistake
+ var block = format.bind(null, new Date(2007, 11 /* Dec */, 31), 'yyyy', {
+ weekStartsOn: NaN,
+ })
+ assert.throws(block, RangeError)
+ })
+
+ it('throws `RangeError` if `options.firstWeekContainsDate` is not convertable to 1, 2, ..., 7 or undefined', function () {
+ // $ExpectedMistake
+ var block = format.bind(null, new Date(2007, 11 /* Dec */, 31), 'yyyy', {
+ firstWeekContainsDate: NaN,
+ })
+ assert.throws(block, RangeError)
+ })
+
+ it('throws RangeError exception if the format string contains an unescaped latin alphabet character', function () {
+ assert.throws(format.bind(null, date, 'yyyy-MM-dd-nnnn'), RangeError)
+ })
+
+ it('throws TypeError exception if passed less than 2 arguments', function () {
+ assert.throws(format.bind(null), TypeError)
+ assert.throws(format.bind(null, 1), TypeError)
+ })
+
+ describe('useAdditionalWeekYearTokens and useAdditionalDayOfYearTokens options', () => {
+ it('throws an error if D token is used', () => {
+ const block = format.bind(null, date, 'yyyy-MM-D')
+ assert.throws(block, RangeError)
+ assert.throws(
+ block,
+ /(Use `d` instead of `D` \(in `yyyy-MM-D`\) for formatting days of the month to the input `Fri Apr 04 1986 10:32:55).*(`; see: https:\/\/git.io\/fxCyr)/g
+ )
+ })
+
+ it('allows D token if useAdditionalDayOfYearTokens is set to true', () => {
+ const result = format(date, 'yyyy-MM-D', {
+ useAdditionalDayOfYearTokens: true,
+ })
+ assert.deepEqual(result, '1986-04-94')
+ })
+
+ it('throws an error if DD token is used', () => {
+ const block = format.bind(null, date, 'yyyy-MM-DD')
+ assert.throws(block, RangeError)
+ assert.throws(
+ block,
+ /(Use `dd` instead of `DD` \(in `yyyy-MM-DD`\) for formatting days of the month to the input `Fri Apr 04 1986 10:32:55).*(`; see: https:\/\/git.io\/fxCyr)/g
+ )
+ })
+
+ it('allows DD token if useAdditionalDayOfYearTokens is set to true', () => {
+ const result = format(date, 'yyyy-MM-DD', {
+ useAdditionalDayOfYearTokens: true,
+ })
+ assert.deepEqual(result, '1986-04-94')
+ })
+
+ it('throws an error if YY token is used', () => {
+ const block = format.bind(null, date, 'YY-MM-dd')
+ assert.throws(block, RangeError)
+ assert.throws(
+ block,
+ /(Use `yy` instead of `YY` \(in `YY-MM-dd`\) for formatting years to the input `Fri Apr 04 1986 10:32:55).*(`; see: https:\/\/git.io\/fxCyr)/g
+ )
+ })
+
+ it('allows YY token if useAdditionalWeekYearTokens is set to true', () => {
+ const result = format(date, 'YY-MM-dd', {
+ useAdditionalWeekYearTokens: true,
+ })
+ assert.deepEqual(result, '86-04-04')
+ })
+
+ it('throws an error if YYYY token is used', () => {
+ const block = format.bind(null, date, 'YYYY-MM-dd')
+ assert.throws(block, RangeError)
+ assert.throws(
+ block,
+ /(Use `yyyy` instead of `YYYY` \(in `YYYY-MM-dd`\) for formatting years to the input `Fri Apr 04 1986 10:32:55).*(`; see: https:\/\/git.io\/fxCyr)/g
+ )
+ })
+
+ it('allows YYYY token if useAdditionalWeekYearTokens is set to true', () => {
+ const result = format(date, 'YYYY-MM-dd', {
+ useAdditionalWeekYearTokens: true,
+ })
+ assert.deepEqual(result, '1986-04-04')
+ })
+ })
+})