diff options
author | Sebastian <sebasjm@gmail.com> | 2021-08-23 16:46:06 -0300 |
---|---|---|
committer | Sebastian <sebasjm@gmail.com> | 2021-08-23 16:48:30 -0300 |
commit | 38acabfa6089ab8ac469c12b5f55022fb96935e5 (patch) | |
tree | 453dbf70000cc5e338b06201af1eaca8343f8f73 /date-fns/docs | |
parent | f26125e039143b92dc0d84e7775f508ab0cdcaa8 (diff) | |
download | node-vendor-38acabfa6089ab8ac469c12b5f55022fb96935e5.tar.gz node-vendor-38acabfa6089ab8ac469c12b5f55022fb96935e5.tar.bz2 node-vendor-38acabfa6089ab8ac469c12b5f55022fb96935e5.zip |
Diffstat (limited to 'date-fns/docs')
-rw-r--r-- | date-fns/docs/.eslintrc.js | 5 | ||||
-rw-r--r-- | date-fns/docs/Day.js | 15 | ||||
-rw-r--r-- | date-fns/docs/Duration.js | 19 | ||||
-rw-r--r-- | date-fns/docs/Interval.js | 16 | ||||
-rw-r--r-- | date-fns/docs/Locale.js | 64 | ||||
-rw-r--r-- | date-fns/docs/constants.md | 47 | ||||
-rw-r--r-- | date-fns/docs/esm.md | 24 | ||||
-rw-r--r-- | date-fns/docs/fp.md | 70 | ||||
-rw-r--r-- | date-fns/docs/gettingStarted.md | 87 | ||||
-rw-r--r-- | date-fns/docs/i18n.md | 92 | ||||
-rw-r--r-- | date-fns/docs/i18nContributionGuide.md | 921 | ||||
-rw-r--r-- | date-fns/docs/index.js | 147 | ||||
-rw-r--r-- | date-fns/docs/logo.svg | 26 | ||||
-rw-r--r-- | date-fns/docs/logotype.svg | 1 | ||||
-rw-r--r-- | date-fns/docs/timeZones.md | 63 | ||||
-rw-r--r-- | date-fns/docs/unicodeTokens.md | 54 | ||||
-rw-r--r-- | date-fns/docs/upgradeGuide.md | 118 | ||||
-rw-r--r-- | date-fns/docs/webpack.md | 48 |
18 files changed, 1817 insertions, 0 deletions
diff --git a/date-fns/docs/.eslintrc.js b/date-fns/docs/.eslintrc.js new file mode 100644 index 0000000..a40aaa8 --- /dev/null +++ b/date-fns/docs/.eslintrc.js @@ -0,0 +1,5 @@ +module.exports = { + rules: { + 'no-console': 'off' + } +} diff --git a/date-fns/docs/Day.js b/date-fns/docs/Day.js new file mode 100644 index 0000000..42df02d --- /dev/null +++ b/date-fns/docs/Day.js @@ -0,0 +1,15 @@ +/** + * @category Types + * @summary Day type + * + * @description + * The day of the week type alias (`0 | 1 | 2 | 3 | 4 | 5 | 6`). Unlike the date + * (the number of days since the beginningof the month), which starts with 1 + * and is dynamic (can go up to 28, 30, or 31), the day starts with 0 and static + * (always ends at 6). Look at it as an index in an array where Sunday is + * the first element, and Saturday is the last. + * + * @typedef {0 | 1 | 2 | 3 | 4 | 5 | 6} Day + */ +const Day = 0 +module.exports = Day diff --git a/date-fns/docs/Duration.js b/date-fns/docs/Duration.js new file mode 100644 index 0000000..95702b3 --- /dev/null +++ b/date-fns/docs/Duration.js @@ -0,0 +1,19 @@ +/** + * @category Types + * @summary Duration object + * + * @description + * Duration object. + * + * @typedef {Object} Duration + * + * @property {number} [years] + * @property {number} [months] + * @property {number} [weeks] + * @property {number} [days] + * @property {number} [hours] + * @property {number} [minutes] + * @property {number} [seconds] + */ +const Duration = {} +module.exports = Duration diff --git a/date-fns/docs/Interval.js b/date-fns/docs/Interval.js new file mode 100644 index 0000000..15347b6 --- /dev/null +++ b/date-fns/docs/Interval.js @@ -0,0 +1,16 @@ +/** + * @category Types + * @summary An object that combines two dates to represent the time interval. + * + * @description + * An object that combines two dates to represent the time interval. + * + * @typedef {Object} Interval + * @property {Date|Number} start - the start of the interval + * @property {Date|Number} end - the end of the interval + * @throws {RangeError} The start of an interval cannot be after its end + * @throws {RangeError} Date in interval cannot be `Invalid Date` + */ +var Interval = {} + +module.exports = Interval diff --git a/date-fns/docs/Locale.js b/date-fns/docs/Locale.js new file mode 100644 index 0000000..fe0de7b --- /dev/null +++ b/date-fns/docs/Locale.js @@ -0,0 +1,64 @@ +/** + * @category Types + * @summary A locale object. + * + * @description + * A locale object. + * + * If you don't specify a locale in options, default locale is `en-US`. + * + * @typedef {Object} Locale + * + * @property {string} [code] - the locale code (ISO 639-1 + optional country code) + * @property {Function} [formatDistance] - the function that takes a token + * passed by `formatDistance` or `formatDistanceStrict` and payload, + * and returns localized distance in words. + * Required by `formatDistance` and `formatDistanceStrict` + * + * @property {Function} [formatRelative] - the function that takes a token + * passed by `formatRelative` and two dates and returns the localized relative date format. + * Required by `formatRelative` + * + * @property {Object} [localize] - the object with functions used to localize various values. + * Required by `format` and `formatRelative` + * @property {Function} localize.ordinalNumber - the function that localizes an ordinal number + * @property {Function} localize.era - the function that takes 0 or 1 and returns localized era + * @property {Function} localize.quarter - the function that localizes a quarter + * @property {Function} localize.month - the function that localizes a month + * @property {Function} localize.day - the function that localizes a day of the week + * @property {Function} localize.dayPeriod - the function that takes one of the strings + * 'am', 'pm', 'midnight', 'noon', 'morning', 'afternoon', 'evening' or 'night' + * and returns localized time of the day + * + * @property {Object} [formatLong] - the object with functions that return localized formats + * @property {Function} formatLong.date - the function that returns a localized long date format + * @property {Function} formatLong.time - the function that returns a localized long time format + * @property {Function} formatLong.dateTime - the function that returns a localized format of date and time combined + * + * @property {Object} [match] — the object with functions used to match and parse various localized values. + * Required by `parse` + * @property {Function} match.ordinalNumber - the function that parses a localized ordinal number + * @property {Function} match.era - the function that parses a localized era + * @property {Function} match.quarter - the function that parses a localized quarter + * @property {Function} match.month - the function that parses a localized month + * @property {Function} match.day - the function that parses a localized day of the week + * @property {Function} match.dayPeriod - the function that parses a localized time of the day + * + * @property {Object} [options] - an object with locale options. + * @property {0|1|2|3|4|5|6} [options.weekStartsOn=0] - the index of the first day of the week (0 - Sunday). + * Used by `differenceInCalendarWeeks`, `endOfWeek`, `format`, `getWeek`, `getWeekOfMonth`, + * `getWeeksInMonth`, `isSameWeek`, `isSameWeek`, `lastDayOfWeek`, `parse`, `setDay`, + * `setWeek`, `startOfWeek` and `startOfWeekYear` + * @property {1|2|3|4|5|6|7} [options.firstWeekContainsDate=1] - the day of January, + * which is always in the first week of the year. + * Used by `format`, `getWeek`, `getWeekYear`, `parse`, `setWeek`, `setWeekYear` and `startOfWeekYear`. + * + * @throws {RangeError} `locale` must contain `localize` property. Thrown by `format` and `formatRelative` + * @throws {RangeError} `locale` must contain `formatLong` property. Thrown by `format` and `formatRelative` + * @throws {RangeError} `locale` must contain `formatRelative` property. Thrown by `formatRelative` + * @throws {RangeError} `locale` must contain `formatDistance` property. Thrown by `formatDistance` and `formatDistanceStrict` + * @throws {RangeError} `locale` must contain `match` property. Thrown by `parse` + */ +var Locale = {} + +module.exports = Locale diff --git a/date-fns/docs/constants.md b/date-fns/docs/constants.md new file mode 100644 index 0000000..b792fd7 --- /dev/null +++ b/date-fns/docs/constants.md @@ -0,0 +1,47 @@ +# Constants + +date-fns provides with a number of useful constants. + +## Usage + +The constants could be imported from `date-fns/constants` or directly +from `date-fns`: + +```js +import { maxTime } from 'date-fns/constants' +import { minTime } from 'date-fns' + +function isAllowedTime(time) { + return time <= maxTime && time >= minTime +} +``` + +## Constants + +### `maxTime` + +Maximum allowed time: + +```js +import { maxTime } from 'date-fns' + +const isValid = 8640000000000001 <= maxTime +//=> false + +new Date(8640000000000001) +//=> Invalid Date +``` + +### `minTime` + +Minimum allowed time: + +```js +import { minTime } from 'date-fns' + +const isValid = -8640000000000001 >= minTime +//=> false + +new Date(-8640000000000001) +//=> Invalid Date +``` diff --git a/date-fns/docs/esm.md b/date-fns/docs/esm.md new file mode 100644 index 0000000..a3fcfa8 --- /dev/null +++ b/date-fns/docs/esm.md @@ -0,0 +1,24 @@ +# ECMAScript Modules + +**date-fns** v2.x provides support for +[ECMAScript Modules](http://www.ecma-international.org/ecma-262/6.0/#sec-modules) +that enables tree-shaking for bundlers, like [rollup.js](http://rollupjs.org) +and [webpack](https://webpack.js.org). + +If you have tree-shaking enabled in your bundler, just import functions normally: + +```javascript +import { format, parse } from 'date-fns' +import { enUS, eo } from 'date-fns/locale' +import { addDays, addHours } from 'date-fns/fp' +``` + +In TypeScript, now you can import individual functions in more idiomatic way: + +```typescript +// Before +import * as format from 'date-fns/format' + +// Now +import format from 'date-fns/format' +``` diff --git a/date-fns/docs/fp.md b/date-fns/docs/fp.md new file mode 100644 index 0000000..fc7ca56 --- /dev/null +++ b/date-fns/docs/fp.md @@ -0,0 +1,70 @@ +# FP Guide + +**date-fns** v2.x provides [functional programming](https://en.wikipedia.org/wiki/Functional_programming) (FP) +friendly functions, like those in [lodash](https://github.com/lodash/lodash/wiki/FP-Guide), +that support [currying](https://en.wikipedia.org/wiki/Currying). + +## Table of Contents + +- [Usage](#usage) + +- [Using Function Composition](#using-function-composition) + +## Usage + +FP functions are provided via `'date-fns/fp'` submodule. + +Functions with options (`format`, `parse`, etc.) have two FP counterparts: +one that has the options object as its first argument and one that hasn't. +The name of the former has `WithOptions` added to the end of its name. + +In **date-fns'** FP functions, the order of arguments is reversed. + +```javascript +import { addYears, formatWithOptions } from 'date-fns/fp' +import { eo } from 'date-fns/locale' +import toUpper from 'lodash/fp/toUpper' // 'date-fns/fp' is compatible with 'lodash/fp'! + +// If FP function has not received enough arguments, it returns another function +const addFiveYears = addYears(5) + +// Several arguments can be curried at once +const dateToString = formatWithOptions({ locale: eo }, 'd MMMM yyyy') + +const dates = [ + new Date(2017, 0 /* Jan */, 1), + new Date(2017, 1 /* Feb */, 11), + new Date(2017, 6 /* Jul */, 2) +] + +const formattedDates = dates.map(addFiveYears).map(dateToString).map(toUpper) +//=> ['1 JANUARO 2022', '11 FEBRUARO 2022', '2 JULIO 2022'] +``` + +## Using Function Composition + +The main advantage of FP functions is support of functional-style +[function composing](https://medium.com/making-internets/why-using-chain-is-a-mistake-9bc1f80d51ba). + +In the example above, you can compose `addFiveYears`, `dateToString` and `toUpper` into a single function: + +```javascript +const formattedDates = dates.map((date) => toUpper(dateToString(addFiveYears(date)))) +``` + +Or you can use `compose` function provided by [lodash](https://lodash.com) to do the same in more idiomatic way: + +```javascript +import compose from 'lodash/fp/compose' + +const formattedDates = dates.map(compose(toUpper, dateToString, addFiveYears)) +``` + +Or if you prefer natural direction of composing (as opposed to the computationally correct order), +you can use lodash' `flow` instead: + +```javascript +import flow from 'lodash/fp/flow' + +const formattedDates = dates.map(flow(addFiveYears, dateToString, toUpper)) +```
\ No newline at end of file diff --git a/date-fns/docs/gettingStarted.md b/date-fns/docs/gettingStarted.md new file mode 100644 index 0000000..51249b8 --- /dev/null +++ b/date-fns/docs/gettingStarted.md @@ -0,0 +1,87 @@ +# Getting Started + +## Table of Contents + +- [Introduction](#introduction) + +- [Submodules](#submodules) + +- [Installation](#installation) + +## Introduction + +**date-fns** provides the most comprehensive, yet simple and consistent toolset +for manipulating **JavaScript dates** in **a browser** & **Node.js**. + +**date-fns** is like [lodash](https://lodash.com) for dates. It has +[**140+ functions** for all occasions](https://date-fns.org/docs/). + +```js +import { format, compareAsc } from 'date-fns' + +format(new Date(2014, 1, 11), 'MM/dd/yyyy') +//=> '02/11/2014' + +const dates = [ + new Date(1995, 6, 2), + new Date(1987, 1, 11), + new Date(1989, 6, 10), +] +dates.sort(compareAsc) +//=> [ +// Wed Feb 11 1987 00:00:00, +// Mon Jul 10 1989 00:00:00, +// Sun Jul 02 1995 00:00:00 +// ] +``` + +## Submodules + +**date-fns** includes some optional features as submodules in the npm package. +Here is the list of them, in order of nesting: + +- FP — functional programming-friendly variations of the functions. See [FP Guide](https://date-fns.org/docs/FP-Guide); + +- UTC (in development) — variations of the functions which calculate dates in UTC±00:00 timezone. + +The later submodules are also included inside the former if you want to use multiple features from the list. + +To use submodule features, [install the npm package](#npm) and then import a function from a submodule: + +```js +// The main submodule: +import addDays from 'date-fns/addDays' + +// FP variation: +import addDays from 'date-fns/fp/addDays' + +// UTC variation: +import addDays from 'date-fns/utc/addDays' + +// Both FP and UTC: +import addDays from 'date-fns/fp/utc/addDays' + +// With tree-shaking enabled: +import { addDays, format } from 'date-fns/fp' +``` + +## Installation + +The library is available as an [npm package](https://www.npmjs.com/package/date-fns). + +To install the package, run: + +```bash +npm install date-fns --save +# or +yarn add date-fns +``` + +Start using: + +```js +import { formatDistance, subDays } from 'date-fns' + +formatDistance(subDays(new Date(), 3), new Date(), { addSuffix: true }) +//=> "3 days ago" +``` diff --git a/date-fns/docs/i18n.md b/date-fns/docs/i18n.md new file mode 100644 index 0000000..4986e62 --- /dev/null +++ b/date-fns/docs/i18n.md @@ -0,0 +1,92 @@ +# Internationalization + +## Table of Contents + +- [Usage](#usage) + +- [Adding New Language](#adding-new-language) + +## Usage + +There are just a few functions that support I18n: + +- [`format`](https://date-fns.org/docs/format) +- [`formatDistance`](https://date-fns.org/docs/formatDistance) +- [`formatDistanceStrict`](https://date-fns.org/docs/formatDistanceStrict) +- [`formatRelative`](https://date-fns.org/docs/formatRelative) + +To use a locale, you need to require it and then pass +as an option to a function: + +```js +import { formatDistance } from 'date-fns' +// Require Esperanto locale +import { eo } from 'date-fns/locale' + +const result = formatDistance( + new Date(2016, 7, 1), + new Date(2015, 0, 1), + {locale: eo} // Pass the locale as an option +) +//=> 'pli ol 1 jaro' +``` + +It might seem complicated to require and pass locales as options, +but unlike Moment.js which bloats your build with all the locales +by default date-fns forces developer to manually require locales when needed. +To make API simple, we encourage you to write tiny wrappers and use those +instead of original functions: + +```js +// app/_lib/format.js + +import { format } from 'date-fns' +import { enGB, eo, ru } from 'date-fns/locale' + +const locales = {enGB, eo, ru} + +// by providing a default string of 'PP' or any of its variants for `formatStr` +// it will format dates in whichever way is appropriate to the locale +export default function (date, formatStr = 'PP') { + return format(date, formatStr, { + locale: locales[window.__localeId__] // or global.__localeId__ + }) +} + +// Later: + +import format from 'app/_lib/format' + +window.__localeId__ = 'enGB' +format(friday13, 'EEEE d') +//=> 'Friday 13' + +window.__localeId__ = 'eo' +format(friday13, 'EEEE d') +//=> 'vendredo 13' + +// If the format string is omitted, it will take the default for the locale. +window.__localeId__ = 'enGB' +format(friday13) +//=> Jul 13, 2019 + +window.__localeId__ = 'eo' +format(friday13) +//=> 2019-jul-13 + +``` + +## Adding New Language + +At the moment there is no definitive guide, so if you feel brave enough, +use this quick guide: + +- First of all, [create an issue](https://github.com/date-fns/date-fns/issues/new?title=XXX%20language%20support) + so you won't overlap with others. +- A detailed explanation of how to [add a new locale](https://github.com/date-fns/date-fns/blob/master/docs/i18nContributionGuide.md#adding-a-new-locale). +- Use [English locale](https://github.com/date-fns/date-fns/tree/master/src/locale/en-US) + as the basis and then incrementally adjust the tests and the code. +- Directions on [adding a locale with the same language as another locale](https://github.com/date-fns/date-fns/blob/master/docs/i18nContributionGuide.md#creating-a-locale-with-the-same-language-as-another-locale). +- If you have questions or need guidance, leave a comment in the issue. + +Thank you for your support! diff --git a/date-fns/docs/i18nContributionGuide.md b/date-fns/docs/i18nContributionGuide.md new file mode 100644 index 0000000..3f4ef8e --- /dev/null +++ b/date-fns/docs/i18nContributionGuide.md @@ -0,0 +1,921 @@ +# I18n Contribution Guide + +## Table of Contents + +- [Adding a new locale](#adding-a-new-locale) + + - [Choosing a directory name for a locale](#choosing-a-directory-name-for-a-locale) + + - [index.js](#index.js) + + - [localize](#localize) + + - [localize.ordinalNumber](#localize.ordinalnumber) + + - [localize.era and using buildLocalizeFn function](#localize.era-and-using-buildlocalizefn-function) + + - [Formatting localizers](#formatting-localizers) + + - [localize.quarter](#localize.quarter) + + - [localize.month](#localize.month) + + - [localize.day](#localize.day) + + - [localize.dayPeriod](#localize.dayperiod) + + - [formatLong](#formatlong) + + - [formatLong.dateFormats](#formatlong.dateformats) + + - [formatLong.timeFormats](#formatlong.timeformats) + + - [formatLong.dateTimeFormats](#formatlong.datetimeformats) + + - [formatRelative](#formatrelative) + + - [match](#match) + + - [formatDistance](#formatdistance) + + - [Tests](#tests) + +- [Creating a locale with the same language as another locale](#creating-a-locale-with-the-same-language-as-another-locale) + +## Adding a new locale + +To add a new locale: + +- [Choose a directory name for it](#choosing-a-directory-name-for-a-locale). + +- Copy the content of an existing locale (e.g. `en-US`) into the newly created directory. + +- Replace the values in the content with yours file-by-file. + Use [CLDR data](https://www.unicode.org/cldr/charts/32/summary/root.html) + as a point of reference which values to choose. + +All locales contain a number of properties: + +- [`formatDistance`](#formatdistance) — distance localizer function used by `formatDistance` and `formatDistanceStrict`. +- [`formatLong`](#formatlong) — contains long date localizer functions used by `format` and `formatRelative`. +- [`formatRelative`](#formatrelative) — relative date localizer function used by `formatRelative`. +- [`localize`](#localize) — contains functions, which localize the various date values. Required by `format` and `formatRelative`. +- [`match`](#match) — contains functions to parse date values. Required by `parse`. +- [`options`](#indexjs) — contains the index of the first day of the week for functions such as `startOfWeek`, + and the value which determines the first week of the year + for functions like `setWeek`. + +### Choosing a directory name for a locale + +Use the four letter code for the directory name (e.g. `en-GB`), + +Use the two/three letter code: + +- if the language code and the country code are the same (e.g. `pt` instead of `pt-PT`). + +- if the language is used in only one country (e.g. `fil` instead of `fil-PH`). + +- if all countries who use the language +also use the same regional standards: the first day of the week, +the week numbering (see: https://en.wikipedia.org/wiki/Week#Week_numbering), +calendar date format (see: https://en.wikipedia.org/wiki/Calendar_date) +and date representation (see: https://en.wikipedia.org/wiki/Date_and_time_representation_by_country +and: https://en.wikipedia.org/wiki/Date_format_by_country) +(e.g. `ca` instead of `ca-ES` and `ca-AD`). + +### index.js + +Locale's `index.js` is where all the properties of the locale are combined in a single file, +documented in JSDoc format. + +```javascript +import formatDistance from './_lib/formatDistance/index.js' +import formatLong from './_lib/formatLong/index.js' +import formatRelative from './_lib/formatRelative/index.js' +import localize from './_lib/localize/index.js' +import match from './_lib/match/index.js' + +/** + * @type {Locale} + * @category Locales + * + * // Name of the locale. + * // Inside the parentheses - name of the country - if the locale uses the four letter code, e.g. en-US, fr-CA or pt-BR. + * @summary English locale (United States). + * + * // Name of the language (used by https://date-fns.org/ website) + * @language English + * + * // ISO 639-2 code. See the list here: + * // https://www.loc.gov/standards/iso639-2/php/code_list.php + * // Used by https://date-fns.org/ to detect the list of the countries that uses the language. + * @iso-639-2 eng + * + * // Authors of the locale (including anyone who corrected or fixed the locale) + * @author Sasha Koss [@kossnocorp]{@link https://github.com/kossnocorp} + * @author Lesha Koss [@leshakoss]{@link https://github.com/leshakoss} + */ +var locale = { + code: 'en', + formatDistance: formatDistance, + formatLong: formatLong, + formatRelative: formatRelative, + localize: localize, + match: match, + options: { + // Index of the first day of the week. + // Sunday is 0, Monday is 1, Saturday is 6. + weekStartsOn: 0, + + // Nth of January which is always in the first week of the year. See: + // https://en.wikipedia.org/wiki/Week#Week_numbering + // http://www.pjh2.de/datetime/weeknumber/wnd.php?l=en + firstWeekContainsDate: 1 + } +} + +export default locale +``` + +### localize + +Put this object in `_lib/localize/index.js` inside your locale directory. +Contains a number of functions for used by `format`: + +```js +var localize = { + ordinalNumber, + era, + quarter, + month, + day, + dayPeriod +} + +export default localize +``` + +#### localize.ordinalNumber + +Function that takes a numeric argument and returns a string with ordinal number: + +```js +// In `en-US` locale: +function ordinalNumber (dirtyNumber, dirtyOptions) { + var number = Number(dirtyNumber) + + var rem100 = number % 100 + if (rem100 > 20 || rem100 < 10) { + switch (rem100 % 10) { + case 1: + return number + 'st' + case 2: + return number + 'nd' + case 3: + return number + 'rd' + } + } + return number + 'th' +} + +var localize = { + ordinalNumber: ordinalNumber, + // ... +} +``` + +If the form of the ordinal number depends on the grammatical case (or other grammatical structures), +use `options.unit` argument which could be one of the values 'year', 'quarter', 'month', 'week', +'date', 'dayOfYear', 'day', 'hour', 'minute' or 'second': + +```js +// In `ru` locale: +function ordinalNumber (dirtyNumber, dirtyOptions) { + var options = dirtyOptions || {} + var unit = String(options.unit) + var suffix + + if (unit === 'date') { + suffix = '-е' + } else if (unit === 'week' || unit === 'minute' || unit === 'second') { + suffix = '-я' + } else { + suffix = '-й' + } + + return dirtyNumber + suffix +} +``` + +#### localize.era and using buildLocalizeFn function + +Localizes a numeric era. Takes either 0 or 1 as the first argument. +As with many of the `localize` functions, they can be generated by built-in +`buildLocalizeFn` function. + +From CLDR chart, use ['Date & Time'/'Gregorian'/'Eras'](https://www.unicode.org/cldr/charts/32/summary/en.html#1771) values. + +```js +// In `en-US` locale: +import buildLocalizeFn from '../../../_lib/buildLocalizeFn/index.js' + +var eraValues = { + narrow: ['B', 'A'], + abbreviated: ['BC', 'AD'], + wide: ['Before Christ', 'Anno Domini'] +} + +var localize = { + // ... + era: buildLocalizeFn({ + values: eraValues, + defaultWidth: 'wide' + }), + // ... +} + +export default localize +``` + +General usage of the function: + +```js +var result = locale.localize.era(1, {width: 'abbreviated'}) +//=> 'AD' +``` + +If `width` is not provided or the `values` object does not contain values for the provided width, +`defaultWidth` will be used. `defaultWidth` should indicate the longest form of the localized value. +The same is true for all other `localize` functions. +`width` for `localize.era` function could be either 'narrow', 'abbreviated' or 'wide'. + +```js +var result = locale.localize.era(1, {width: 'foobar'}) +//=> 'Anno Domini' +``` + +#### Formatting localizers + +For some languages, there is a difference for "stand-alone" localizers and "formatting" localizers. +"Stand-alone" means that the resulting value should make grammatical sense without context. +"Formatting" means that the resulting value should be declined using the grammar rules of the language +as if the value was a part of a date. +For example, for languages with grammatical cases, stand-alone month could be in the nominative case ("January"), +and formatting month could decline as a part of phrase "1st of January". +In this case, use parameters `formattingValues` and `defaultFormattingWidth` of `buildLocalizeFn` function. + +Any localizer could be stand-alone and formatting. +Check the CLDR chart for the unit to see if stand-alone and formatting values are different for a certain unit. +If there's no difference (usually it happens in languages without grammatical cases), +parameters `formattingValues` and `defaultFormattingWidth` are not needed. + +In this example, in Russian language a stand-alone month is in the nominative case ("январь"), +and formatting month is in the genitive case ("января" as in "1-е января"). Notice the different endings: + +```js +// In `ru` locale: +var monthValues = { + narrow: ['Я', 'Ф', 'М', 'А', 'М', 'И', 'И', 'А', 'С', 'О', 'Н', 'Д'], + abbreviated: ['янв.', 'фев.', 'март', 'апр.', 'май', 'июнь', 'июль', 'авг.', 'сент.', 'окт.', 'нояб.', 'дек.'], + wide: ['январь', 'февраль', 'март', 'апрель', 'май', 'июнь', 'июль', 'август', 'сентябрь', 'октябрь', 'ноябрь', 'декабрь'] +} +var formattingMonthValues = { + narrow: ['Я', 'Ф', 'М', 'А', 'М', 'И', 'И', 'А', 'С', 'О', 'Н', 'Д'], + abbreviated: ['янв.', 'фев.', 'мар.', 'апр.', 'мая', 'июн.', 'июл.', 'авг.', 'сент.', 'окт.', 'нояб.', 'дек.'], + wide: ['января', 'февраля', 'марта', 'апреля', 'мая', 'июня', 'июля', 'августа', 'сентября', 'октября', 'ноября', 'декабря'] +} + +var localize = { + // ... + month: buildLocalizeFn({ + values: monthValues, + defaultWidth: 'wide', + formattingValues: formattingMonthValues, + defaultFormattingWidth: 'wide' + }), + // ... +} + +export default localize +``` + +#### localize.quarter + +Localizes a quarter. Takes 1, 2, 3 or 4 as the first argument. +`width` could be either 'narrow', 'abbreviated' or 'wide'. +From CLDR chart, use ['Date & Time'/'Gregorian'/'Quarters'](https://www.unicode.org/cldr/charts/32/summary/en.html#1781) values. + +```js +// In `en-US` locale: +import buildLocalizeFn from '../../../_lib/buildLocalizeFn/index.js' + +var quarterValues = { + narrow: ['1', '2', '3', '4'], + abbreviated: ['Q1', 'Q2', 'Q3', 'Q4'], + wide: ['1st quarter', '2nd quarter', '3rd quarter', '4th quarter'] +} + +var localize = { + // ... + quarter: buildLocalizeFn({ + values: quarterValues, + defaultWidth: 'wide', + argumentCallback: function (quarter) { + return Number(quarter) - 1 + } + }), + // ... +} + +export default localize +``` + +Note the usage of `argumentCallback` here. It converts the value passed into `localize.quarter` function +(one of 1, 2, 3 or 4) into the index of the values array inside `quarterValues` (one of 0, 1, 2 or 3). + +#### localize.month + +Localizes a month. Takes numbers between 0 (for January) and 11 (for December). +`width` could be either 'narrow', 'abbreviated' or 'wide'. +From CLDR chart, use ['Date & Time'/'Gregorian'/'Months'](https://www.unicode.org/cldr/charts/32/summary/en.html#1793) values. + +```js +// In `en-US` locale: +import buildLocalizeFn from '../../../_lib/buildLocalizeFn/index.js' + +var monthValues = { + narrow: ['J', 'F', 'M', 'A', 'M', 'J', 'J', 'A', 'S', 'O', 'N', 'D'], + abbreviated: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'], + wide: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'] +} + +var localize = { + // ... + month: buildLocalizeFn({ + values: monthValues, + defaultWidth: 'wide' + }), + // ... +} + +export default localize +``` + +**NOTE**: in English, the names of days of the week and months are capitalized. +Check if the same is true for the language you're working on. +Generally, formatted dates should look like they are in the middle of a sentence, +e.g. in Spanish language the weekdays and months should be in the lowercase: + +```js +// In `es` locale: +var monthValues = { + narrow: ['E', 'F', 'M', 'A', 'M', 'J', 'J', 'A', 'S', 'O', 'N', 'D'], + abbreviated: ['ene.', 'feb.', 'mar.', 'abr.', 'may.', 'jun.', 'jul.', 'ago.', 'sep.', 'oct.', 'nov.', 'dic.'], + wide: ['enero', 'febrero', 'marzo', 'abril', 'mayo', 'junio', 'julio', 'agosto', 'septiembre', 'octubre', 'noviembre', 'diciembre'] +} +``` + +`monthValues.narrow` are usually capitalized in every language. Check the CLDR chart for your language. + +#### localize.day + +Localizes a week day. Takes numbers between 0 (for Sunday) and 6 (for Saturday). +`width` could be either 'narrow', 'short', 'abbreviated' or 'wide'. +From CLDR chart, use ['Date & Time'/'Gregorian'/'Days'](https://www.unicode.org/cldr/charts/32/summary/en.html#1829) values. + +```js +// In `en-US` locale: +import buildLocalizeFn from '../../../_lib/buildLocalizeFn/index.js' + +var dayValues = { + narrow: ['S', 'M', 'T', 'W', 'T', 'F', 'S'], + short: ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'], + abbreviated: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'], + wide: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'] +} + +var localize = { + // ... + day: buildLocalizeFn({ + values: dayValues, + defaultWidth: 'wide' + }), + // ... +} + +export default localize +``` + +**NOTE**: the rules of capitalization from `localize.month` are also true for `localize.day`. + +#### localize.dayPeriod + +Localizes a certain day period. +Could take of these strings as the argument: 'am', 'pm', 'midnight', 'noon', 'morning', 'afternoon', 'evening', 'night'. +`width` could be either 'narrow', 'abbreviated' or 'wide'. +From CLDR chart, use ['Date & Time'/'Gregorian'/'Day periods'](https://www.unicode.org/cldr/charts/32/summary/en.html#1857) values. + +```js +// In `en-US` locale: +import buildLocalizeFn from '../../../_lib/buildLocalizeFn/index.js' + +var dayPeriodValues = { + narrow: { + am: 'a', + pm: 'p', + midnight: 'mi', + noon: 'n', + morning: 'in the morning', + afternoon: 'in the afternoon', + evening: 'in the evening', + night: 'at night' + }, + abbreviated: { + am: 'AM', + pm: 'PM', + midnight: 'midnight', + noon: 'noon', + morning: 'in the morning', + afternoon: 'in the afternoon', + evening: 'in the evening', + night: 'at night' + }, + wide: { + am: 'a.m.', + pm: 'p.m.', + midnight: 'midnight', + noon: 'noon', + morning: 'in the morning', + afternoon: 'in the afternoon', + evening: 'in the evening', + night: 'at night' + } +} + +var localize = { + // ... + dayPeriod: buildLocalizeFn({ + values: dayPeriodValues, + defaultWidth: 'wide' + }) +} + +export default localize +``` + +### formatLong + +Put this object in `_lib/formatLong/index.js` inside your locale directory. +Locale date formats written in `format` token string format. +See the list of tokens: https://date-fns.org/docs/format +Use https://en.wikipedia.org/wiki/Date_format_by_country and CLDR chart as the reference. + +#### formatLong.dateFormats + +Use ['Date & Time'/'Gregorian'/'Formats - Standard - Date Formats'](https://www.unicode.org/cldr/charts/32/summary/en.html#1901) values +from the CLDR chart as a reference. + +```js +// In `en-US` locale +import buildFormatLongFn from '../../../_lib/buildFormatLongFn/index.js' + +var dateFormats = { + full: 'EEEE, MMMM do, y', + long: 'MMMM do, y', + medium: 'MMM d, y', + short: 'MM/dd/yyyy' +} + +var formatLong = { + date: buildFormatLongFn({ + formats: dateFormats, + defaultWidth: 'full' + }), + // ... +} + +export default formatLong +``` + +`dateFormats.long` usually contains the longest form of writing the year, the month, and the day of the month. +Use ordinal day of the month ('do' token) where applicable (date-fns, unlike CLDR supports ordinal numbers). + +`dateFormats.full` contains the same but with the day of the week. + +`dateFormats.medium` contains the same values as `dateFormats.long`, but with short form of month and non-ordinal day. + +`dateFormats.short` usually contains strictly numerical form of the date. +Pay attention to the order of units (big-, little- or middle-endian) + +#### formatLong.timeFormats + +Use ['Date & Time'/'Gregorian'/'Formats - Standard - Time Formats'](https://www.unicode.org/cldr/charts/32/summary/en.html#1906) values +from the CLDR chart as a reference. + +Use some variation of 'h:mm aa' for 12-hour clock locales or 'H:mm' for 24-hour clock locales. Use the local time separator. + +```js +// In `en-US` locale +import buildFormatLongFn from '../../../_lib/buildFormatLongFn/index.js' + +var timeFormats = { + full: 'h:mm:ss a zzzz', + long: 'h:mm:ss a z', + medium: 'h:mm:ss a', + short: 'h:mm a' +} + +var formatLong = { + // ... + time: buildFormatLongFn({ + formats: timeFormats, + defaultWidth: 'full' + }), + // ... +} + +export default formatLong +``` + +#### formatLong.dateTimeFormats + +Use +['Date & Time'/'Gregorian'/'Formats - Standard - Date & Time Combination Formats'](https://www.unicode.org/cldr/charts/32/summary/en.html#1910) +values from the CLDR chart. + +```js +// In `en-US` locale +import buildFormatLongFn from '../../../_lib/buildFormatLongFn/index.js' + +var dateTimeFormats = { + full: "{{date}} 'at' {{time}}", + long: "{{date}} 'at' {{time}}", + medium: '{{date}}, {{time}}', + short: '{{date}}, {{time}}' +} + +var formatLong = { + // ... + dateTime: buildFormatLongFn({ + formats: dateTimeFormats, + defaultWidth: 'full' + }) +} + +export default formatLong +``` + +'{{date}}' and '{{time}}' from the strings will be replaced with the date and time respectively. + +### formatRelative + +Put this function in `_lib/formatRelative/index.js` inside your locale directory. +Relative date formats written in `format` token string format. +See the list of tokens: https://date-fns.org/docs/format. +Has to process `lastWeek`, `yesterday`, `today`, `tomorrow`, `nextWeek` and `other` tokens. + +```javascript +// In `en-US` locale +var formatRelativeLocale = { + lastWeek: "'last' eeee 'at' p", + yesterday: "'yesterday at' p", + today: "'today at' p", + tomorrow: "'tomorrow at' p", + nextWeek: "eeee 'at' p", + other: 'P' +} + +export default function formatRelative (token, date, baseDate, options) { + return formatRelativeLocale[token] +} +``` + +You can use `date` and `baseDate` supplied to the function for the difficult situations +(e.g. grammatical genders and cases of the days of the week) +Both `date` and `baseDate` are converted to UTC timezone, which means +that you should use UTC methods to take the date values (i.e. `date.getUTCDay()` instead of `date.getDay()`). +You can use UTC functions from `src/_lib` in date-fns root directory if they are available. +Don't forget to pass `options` object to them! +Example is below. Note the different grammatical case for weekdays (accusative instead of nominative) +and declension of word "прошлый" which depends on the grammatical gender of the weekday: + +```javascript +// In `ru` locale +import isSameUTCWeek from '../../../../_lib/isSameUTCWeek/index.js' + +var accusativeWeekdays = ['воскресенье', 'понедельник', 'вторник', 'среду', 'четверг', 'пятницу', 'субботу'] + +function lastWeek (day) { + var weekday = accusativeWeekdays[day] + + switch (day) { + case 0: + return "'в прошлое " + weekday + " в' p" + case 1: + case 2: + case 4: + return "'в прошлый " + weekday + " в' p" + case 3: + case 5: + case 6: + return "'в прошлую " + weekday + " в' p" + } +} + +function thisWeek (day) { + // ... +} + +function nextWeek (day) { + // ... +} + +var formatRelativeLocale = { + lastWeek: function (date, baseDate, options) { + var day = date.getUTCDay() + if (isSameUTCWeek(date, baseDate, options)) { + return thisWeek(day) + } else { + return lastWeek(day) + } + }, + yesterday: "'вчера в' p", + today: "'сегодня в' p", + tomorrow: "'завтра в' p", + nextWeek: function (date, baseDate, options) { + var day = date.getUTCDay() + if (isSameUTCWeek(date, baseDate, options)) { + return thisWeek(day) + } else { + return nextWeek(day) + } + }, + other: 'P' +} + +export default function formatRelative (token, date, baseDate, options) { + var format = formatRelativeLocale[token] + + if (typeof format === 'function') { + return format(date, baseDate, options) + } + + return format +} +``` + +### match + +Put this object in `_lib/match/index.js` inside your locale directory. +Contains the functions used by `parse` to parse a localized value: + +```js +// In `en-US` locale: +import buildMatchPatternFn from '../../../_lib/buildMatchPatternFn/index.js' +import buildMatchFn from '../../../_lib/buildMatchFn/index.js' + +var matchOrdinalNumberPattern = /^(\d+)(th|st|nd|rd)?/i +var parseOrdinalNumberPattern = /\d+/i + +var matchEraPatterns = { + narrow: /^(b|a)/i, + abbreviated: /^(b\.?\s?c\.?|b\.?\s?c\.?\s?e\.?|a\.?\s?d\.?|c\.?\s?e\.?)/i, + wide: /^(before christ|before common era|anno domini|common era)/i +} +var parseEraPatterns = { + any: [/^b/i, /^(a|c)/i] +} + +var matchQuarterPatterns = { + narrow: /^[1234]/i, + abbreviated: /^q[1234]/i, + wide: /^[1234](th|st|nd|rd)? quarter/i +} +var parseQuarterPatterns = { + any: [/1/i, /2/i, /3/i, /4/i] +} + +var matchMonthPatterns = { + narrow: /^[jfmasond]/i, + abbreviated: /^(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)/i, + wide: /^(january|february|march|april|may|june|july|august|september|october|november|december)/i +} +var parseMonthPatterns = { + narrow: [/^j/i, /^f/i, /^m/i, /^a/i, /^m/i, /^j/i, /^j/i, /^a/i, /^s/i, /^o/i, /^n/i, /^d/i], + any: [/^ja/i, /^f/i, /^mar/i, /^ap/i, /^may/i, /^jun/i, /^jul/i, /^au/i, /^s/i, /^o/i, /^n/i, /^d/i] +} + +var matchDayPatterns = { + narrow: /^[smtwf]/i, + short: /^(su|mo|tu|we|th|fr|sa)/i, + abbreviated: /^(sun|mon|tue|wed|thu|fri|sat)/i, + wide: /^(sunday|monday|tuesday|wednesday|thursday|friday|saturday)/i +} +var parseDayPatterns = { + narrow: [/^s/i, /^m/i, /^t/i, /^w/i, /^t/i, /^f/i, /^s/i], + any: [/^su/i, /^m/i, /^tu/i, /^w/i, /^th/i, /^f/i, /^sa/i] +} + +var matchDayPeriodPatterns = { + narrow: /^(a|p|mi|n|(in the|at) (morning|afternoon|evening|night))/i, + any: /^([ap]\.?\s?m\.?|midnight|noon|(in the|at) (morning|afternoon|evening|night))/i +} +var parseDayPeriodPatterns = { + any: { + am: /^a/i, + pm: /^p/i, + midnight: /^mi/i, + noon: /^no/i, + morning: /morning/i, + afternoon: /afternoon/i, + evening: /evening/i, + night: /night/i + } +} + +var match = { + ordinalNumber: buildMatchPatternFn({ + matchPattern: matchOrdinalNumberPattern, + parsePattern: parseOrdinalNumberPattern, + valueCallback: function (value) { + return parseInt(value, 10) + } + }), + + era: buildMatchFn({ + matchPatterns: matchEraPatterns, + defaultMatchWidth: 'wide', + parsePatterns: parseEraPatterns, + defaultParseWidth: 'any' + }), + + quarter: buildMatchFn({ + matchPatterns: matchQuarterPatterns, + defaultMatchWidth: 'wide', + parsePatterns: parseQuarterPatterns, + defaultParseWidth: 'any', + valueCallback: function (index) { + return index + 1 + } + }), + + month: buildMatchFn({ + matchPatterns: matchMonthPatterns, + defaultMatchWidth: 'wide', + parsePatterns: parseMonthPatterns, + defaultParseWidth: 'any' + }), + + day: buildMatchFn({ + matchPatterns: matchDayPatterns, + defaultMatchWidth: 'wide', + parsePatterns: parseDayPatterns, + defaultParseWidth: 'any' + }), + + dayPeriod: buildMatchFn({ + matchPatterns: matchDayPeriodPatterns, + defaultMatchWidth: 'any', + parsePatterns: parseDayPeriodPatterns, + defaultParseWidth: 'any' + }) +} + +export default match +``` + +These functions mirror those in `localize`. + +For `matchPatterns` the patterns should match the whole meaningful word for the parsed value +(which will be cut from the string in the process of parsing). +`parsePatterns` contains patterns to detect one of the values from the result of `matchPatterns` +Note that the patterns for `parsePatterns` don't necessary contain the whole word: + +```javascript +// In `en-US` locale: +var parseDayPatterns = { + narrow: [/^s/i, /^m/i, /^t/i, /^w/i, /^t/i, /^f/i, /^s/i], + any: [/^su/i, /^m/i, /^tu/i, /^w/i, /^th/i, /^f/i, /^sa/i] +} +``` + +but only the bare minimum to parse the value. + +Also note that all patterns have "case-insensitive" flags +to match as much arbitrary user input as possible. For the same reason, try to match +any variation of diacritical marks: + +```javascript +// In `eo` locale: +var matchDayPatterns = { + narrow: /^[dlmĵjvs]/i, + short: /^(di|lu|ma|me|(ĵ|jx|jh|j)a|ve|sa)/i, + abbreviated: /^(dim|lun|mar|mer|(ĵ|jx|jh|j)a(ŭ|ux|uh|u)|ven|sab)/i, + wide: /^(diman(ĉ|cx|ch|c)o|lundo|mardo|merkredo|(ĵ|jx|jh|j)a(ŭ|ux|uh|u)do|vendredo|sabato)/i +} +var parseDayPatterns = { + narrow: [/^d/i, /^l/i, /^m/i, /^m/i, /^(j|ĵ)/i, /^v/i, /^s/i], + any: [/^d/i, /^l/i, /^ma/i, /^me/i, /^(j|ĵ)/i, /^v/i, /^s/i] +} +``` + +Here, for the word "dimanĉo" the functions will match also "dimancxo", "dimancho" +and even grammatically incorrect "dimanco". + +Try to match any possible way of writing the word. Don't forget the grammatical cases: + +```javascript +// In `ru` locale: +var matchMonthPatterns = { + narrow: /^[яфмаисонд]/i, + abbreviated: /^(янв|фев|март?|апр|ма[йя]|июн[ья]?|июл[ья]?|авг|сент?|окт|нояб?|дек)/i, + wide: /^(январ[ья]|феврал[ья]|марта?|апрел[ья]|ма[йя]|июн[ья]|июл[ья]|августа?|сентябр[ья]|октябр[ья]|октябр[ья]|ноябр[ья]|декабр[ья])/i +} +``` + +and variations of short weekdays and months: + +```javascript +// In `ru` locale: +var matchDayPatterns = { + narrow: /^[впсч]/i, + short: /^(вс|во|пн|по|вт|ср|чт|че|пт|пя|сб|су)\.?/i, + abbreviated: /^(вск|вос|пнд|пон|втр|вто|срд|сре|чтв|чет|птн|пят|суб).?/i, + wide: /^(воскресень[ея]|понедельника?|вторника?|сред[аы]|четверга?|пятниц[аы]|суббот[аы])/i +} +``` + +(here, the `abbreviated` pattern will match both `вск` and `вос` as the short of `воскресенье` {Sunday}) + +In `match.ordinalNumber` match ordinal numbers as well as non-ordinal numbers: + +```javascript +// In `en-US` locale: +var matchOrdinalNumberPattern = /^(\d+)(th|st|nd|rd)?/i +``` + +Don't forget the grammatical genders: + +```javascript +// In `ru` locale: +var matchOrdinalNumberPattern = /^(\d+)(-?(е|я|й|ое|ье|ая|ья|ый|ой|ий|ый))?/i +``` + +### formatDistance + +`formatDistance` property of locale is a function which takes three arguments: +token passed by date-fns' `formatDistance` function (e.g. 'lessThanXMinutes'), +a number of units to be displayed by the function +(e.g. `locale.formatDistance('lessThanXMinutes', 5)` would display localized 'less than 5 minutes') +and object with options. + +Your best guess is to copy `formatDistance` property from another locale and change the values. + +### Tests + +To test locales we use snapshots. See [`en-US` snapshot](https://github.com/date-fns/date-fns/blob/master/src/locale/en-US/snapshot.md) for an example. + +To generate snapshots, run `yarn locale-snapshots`. The snapshot for the locale +you're working on will appear in the root locale directory (e.g. `src/locales/ru/snapshot.md`). + +Once you are done with the locale, generate the snapshot and review the output values. + +## Creating a locale with the same language as another locale + +Import the locale properties already implemented for the language, +but replace unique properties. + +```javascript +// Same as en-US +import formatDistance from '../en-US/_lib/formatDistance/index.js' +import formatRelative from '../en-US/_lib/formatRelative/index.js' +import localize from '../en-US/_lib/localize/index.js' +import match from '../en-US/_lib/match/index.js' + +// Unique for en-GB +import formatLong from './_lib/formatLong/index.js' + +/** + * @type {Locale} + * @category Locales + * @summary English locale (United Kingdom). + * @language English + * @iso-639-2 eng + * @author John Doe [@example]{@link https://github.com/example} + */ +var locale = { + formatDistance: formatDistance, + formatLong: formatLong, + formatRelative: formatRelative, + localize: localize, + match: match, + + // Unique for en-GB + options: { + weekStartsOn: 1, + firstWeekContainsDate: 4 + } +} + +export default locale +``` diff --git a/date-fns/docs/index.js b/date-fns/docs/index.js new file mode 100644 index 0000000..bd8ee26 --- /dev/null +++ b/date-fns/docs/index.js @@ -0,0 +1,147 @@ +const path = require('path') + +module.exports = { + groups: [ + 'General', + 'Types', + 'Common Helpers', + 'Conversion Helpers', + 'Interval Helpers', + 'Timestamp Helpers', + 'Millisecond Helpers', + 'Second Helpers', + 'Minute Helpers', + 'Hour Helpers', + 'Day Helpers', + 'Weekday Helpers', + 'Week Helpers', + 'ISO Week Helpers', + 'Month Helpers', + 'Quarter Helpers', + 'Year Helpers', + 'ISO Week-Numbering Year Helpers', + 'Decade Helpers', + ], + + staticDocs: [ + { + type: 'markdown', + urlId: 'Getting-Started', + category: 'General', + title: 'Getting Started', + description: 'Introduction & installation instructions', + path: path.join(__dirname, 'gettingStarted.md'), + }, + { + type: 'markdown', + urlId: 'Change-Log', + category: 'General', + title: 'Change Log', + description: 'Changes for each version of the library', + path: path.join(__dirname, '..', 'CHANGELOG.md'), + }, + { + type: 'markdown', + urlId: 'Contributing', + category: 'General', + title: 'Contributing', + description: 'Contribution manual', + path: path.join(__dirname, '..', 'CONTRIBUTING.md'), + }, + { + type: 'markdown', + urlId: 'Constants', + category: 'General', + title: 'Constants', + description: 'Useful constants', + path: path.join(__dirname, 'constants.md'), + }, + { + type: 'markdown', + urlId: 'I18n', + category: 'General', + title: 'I18n', + description: 'Internationalization', + path: path.join(__dirname, 'i18n.md'), + }, + { + type: 'markdown', + urlId: 'I18n-Contribution-Guide', + category: 'General', + title: 'I18n Contribution Guide', + description: 'Locales manual', + path: path.join(__dirname, 'i18nContributionGuide.md'), + }, + { + type: 'markdown', + urlId: 'Time-Zones', + category: 'General', + title: 'Time Zones', + description: 'Time zone functions', + path: path.join(__dirname, 'timeZones.md'), + }, + { + type: 'markdown', + urlId: 'ECMAScript-Modules', + category: 'General', + title: 'ECMAScript Modules', + description: 'Tree-shaking guide', + path: path.join(__dirname, 'esm.md'), + }, + { + type: 'markdown', + urlId: 'webpack', + category: 'General', + title: 'webpack', + description: 'Using date-fns with webpack', + path: path.join(__dirname, 'webpack.md'), + }, + { + type: 'markdown', + urlId: 'FP-Guide', + category: 'General', + title: 'FP Guide', + description: 'Curried functions', + path: path.join(__dirname, 'fp.md'), + }, + { + type: 'markdown', + urlId: 'Unicode-Tokens', + category: 'General', + title: 'Unicode Tokens', + description: 'Usage of the Unicode tokens in parse and format', + path: path.join(__dirname, 'unicodeTokens.md'), + }, + { + type: 'markdown', + urlId: 'Upgrade-Guide', + category: 'General', + title: 'Upgrade guide', + description: 'Changes from v1 to v2', + path: path.join(__dirname, 'upgradeGuide.md'), + }, + { + type: 'markdown', + urlId: 'License', + category: 'General', + title: 'License', + description: 'MIT © Sasha Koss', + path: path.join(__dirname, '..', 'LICENSE.md'), + }, + ], + + sharedDocs: [ + { + fullPath: path.join(__dirname, 'Interval.js'), + }, + { + fullPath: path.join(__dirname, 'Locale.js'), + }, + { + fullPath: path.join(__dirname, 'Duration.js'), + }, + { + fullPath: path.join(__dirname, 'Day.js'), + }, + ], +} diff --git a/date-fns/docs/logo.svg b/date-fns/docs/logo.svg new file mode 100644 index 0000000..212e227 --- /dev/null +++ b/date-fns/docs/logo.svg @@ -0,0 +1,26 @@ +<?xml version="1.0" encoding="UTF-8" standalone="no"?> +<svg width="32px" height="26px" viewBox="0 0 32 26" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"> + <!-- Generator: Sketch 3.7.1 (28215) - http://www.bohemiancoding.com/sketch --> + <title>Slice 1</title> + <desc>Created with Sketch.</desc> + <defs></defs> + <g id="Page-1" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd"> + <g id="date-fns-mini-logo" fill="#770C56"> + <g id="Page-1"> + <g id="logo"> + <g id="Page-1"> + <g id="Solid-logo"> + <g id="White-logo"> + <path d="M0.0773377951,12.9617647 C0.0773377951,10.4657522 0.541359926,8.11201106 1.46941811,5.90047059 C2.39747629,3.68893013 3.73386003,1.72977324 5.47860941,0.0229411764 L8.98665179,0.0229411764 C5.34866372,3.58342956 3.52969697,7.89632761 3.52969697,12.9617647 C3.52969697,18.0272018 5.34866372,22.3400999 8.98665179,25.9005883 L5.47860941,25.9005883 C3.73386003,24.1937561 2.39747629,22.2345993 1.46941811,20.0230588 C0.541359926,17.8115184 0.0773377951,15.4577772 0.0773377951,12.9617647 L0.0773377951,12.9617647 L0.0773377951,12.9617647 L0.0773377951,12.9617647 Z M31.4378137,12.9617647 C31.4378137,15.4577772 30.9737916,17.8115184 30.0457334,20.0230588 C29.1176752,22.2345993 27.7812915,24.1937561 26.0365421,25.9005883 L22.5284998,25.9005883 C26.1664878,22.3400999 27.9854545,18.0272018 27.9854545,12.9617647 C27.9854545,7.89632761 26.1664878,3.58342956 22.5284998,0.0229411764 L26.0365421,0.0229411764 C27.7812915,1.72977324 29.1176752,3.68893013 30.0457334,5.90047059 C30.9737916,8.11201106 31.4378137,10.4657522 31.4378137,12.9617647 L31.4378137,12.9617647 L31.4378137,12.9617647 L31.4378137,12.9617647 Z" id="Parans"></path> + <g id="Hands" transform="translate(12.954081, 1.720588)"> + <rect id="Hand" x="0" y="0" width="2.32013386" height="13.1911764"></rect> + <polygon id="Hand" points="2.3189551 13.1499342 0.815087916 11.6629302 10.2484366 2.3353599 11.7523038 3.82236388 2.3189551 13.1499342"></polygon> + </g> + </g> + </g> + </g> + </g> + </g> + </g> + </g> +</svg>
\ No newline at end of file diff --git a/date-fns/docs/logotype.svg b/date-fns/docs/logotype.svg new file mode 100644 index 0000000..8b2a3a4 --- /dev/null +++ b/date-fns/docs/logotype.svg @@ -0,0 +1 @@ +<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 176 33"><g fill="#770C56" fill-rule="evenodd"><path d="M.1 16.5A22.7 22.7 0 017.1 0h4.4a22 22 0 00-7 16.5 22 22 0 007 16.4H7A22.5 22.5 0 01.1 16.5zm40.2 0a22.7 22.7 0 01-7 16.4H29a22 22 0 007-16.4 22 22 0 00-7-16.5h4.5a22.5 22.5 0 016.9 16.5z" fill-rule="nonzero"/><path d="M16.6 2.2h3v16.7h-3z"/><path d="M19.6 18.9l-2-2L29.7 5.2l2 2zM53.4 17.5c0 2 .5 3.8 1.4 5.2.8 1.4 2.2 2 4.2 2 1.5 0 2.7-.6 3.7-1.9 1-1.3 1.4-3.1 1.4-5.5 0-2.5-.5-4.3-1.5-5.5a4.7 4.7 0 00-3.7-1.7c-1.6 0-3 .6-4 1.8-1 1.3-1.5 3.1-1.5 5.6zm5-10.3c1.4 0 2.7.3 3.7 1 .5.3 1.2 1 2 1.9V.3h3v26.6h-2.9v-2.7a7 7 0 01-2.7 2.6c-1 .5-2.2.8-3.5.8-2.2 0-4-.9-5.6-2.7a10.6 10.6 0 01-2.4-7.2c0-2.9.7-5.3 2.2-7.4a7 7 0 016.1-3zm15.1 14.6c0 1 .4 1.7 1 2.2.8.5 1.6.8 2.5.8 1.2 0 2.3-.3 3.3-.8a4.5 4.5 0 002.7-4.3V17l-1.5.6-1.8.4-2 .2c-1.2.2-2 .4-2.7.8-1 .5-1.5 1.4-1.5 2.7zm8-6.6c.7-.1 1.2-.4 1.4-1 .2-.2.2-.7.2-1.2 0-1.1-.4-1.9-1.1-2.4-.8-.5-2-.8-3.4-.8-1.7 0-3 .5-3.6 1.4-.4.5-.7 1.3-.8 2.3h-3c0-2.4.8-4 2.3-5 1.5-1 3.2-1.4 5.1-1.4 2.3 0 4.2.4 5.6 1.3 1.4.9 2.1 2.2 2.1 4v11.2c0 .3 0 .6.2.8.1.2.4.3.9.3a5 5 0 001 0V27a9 9 0 01-1.1.3h-1c-1.2 0-2-.4-2.5-1.2-.3-.4-.5-1-.6-1.7a8.8 8.8 0 01-7 3.2c-1.7 0-3.2-.6-4.3-1.7a5.4 5.4 0 01-1.8-4c0-1.9.6-3.2 1.7-4.2a8 8 0 014.4-1.9l5.2-.6zm9.9-13h3.3v5.4h3v2.6h-3V23c0 .6.2 1 .7 1.3l1.2.2a15.2 15.2 0 001.2 0v2.5l-1.2.3h-1.3c-1.5 0-2.6-.4-3.1-1.1-.6-.8-.8-1.8-.8-3V10.1h-2.6V7.6h2.6V2.2zm16.8 5a8.8 8.8 0 016.9 3.4c.7 1 1 2.1 1.3 3.4.2 1 .3 2.3.3 4.3h-14.2c0 2 .5 3.5 1.4 4.7.9 1.2 2.2 1.8 4 1.8a5.2 5.2 0 005.3-4h3.2c0 .8-.3 1.6-.8 2.4a7.6 7.6 0 01-5.3 4c-.8.3-1.7.4-2.6.4-2.4 0-4.5-.9-6.2-2.6a10.2 10.2 0 01-2.5-7.4c0-3 .9-5.6 2.6-7.6 1.6-1.9 3.8-2.9 6.6-2.9zm5.2 8.5a8.4 8.4 0 00-1-3.4c-.9-1.5-2.3-2.3-4.4-2.3a5 5 0 00-3.8 1.6c-1 1-1.5 2.4-1.6 4.1h10.8zm5.5-.8h9.1v3.4h-9v-3.4zM132 4.6c0-1.3.3-2.3.7-3 .8-1 2.2-1.6 4.4-1.6a11.4 11.4 0 011.4 0v3a26.4 26.4 0 00-1.2 0c-1 0-1.5.2-1.7.7-.2.6-.3 1.9-.3 4h3.2v2.5h-3.3V27H132V10.2h-2.7V7.7h2.7v-3zm8.6 3h3v2.7c1-1.1 2-2 3-2.4 1-.5 2.1-.8 3.4-.8 2.7 0 4.6 1 5.6 3 .5 1 .8 2.5.8 4.4V27H153V14.7c0-1.2-.2-2.1-.6-2.8-.5-1.2-1.6-1.8-3.1-1.8a4.9 4.9 0 00-4.2 1.8c-.6.6-1 1.3-1.1 2-.2.6-.3 1.6-.3 2.9v10.1h-3.2V7.6zm21.6 13.2c0 1.1.4 2 .8 2.5.8 1 2.3 1.6 4.3 1.6 1.2 0 2.2-.2 3.2-.8.9-.5 1.3-1.3 1.3-2.4a2 2 0 00-1-1.9c-.5-.3-1.5-.6-2.9-1l-2.5-.6c-1.7-.4-3-.8-3.7-1.3a4.1 4.1 0 01-2-3.7c0-1.8.6-3.3 1.9-4.4 1.3-1.2 3-1.7 5.3-1.7 3 0 5 .8 6.3 2.5.8 1.1 1.2 2.3 1.2 3.5h-3c-.1-.7-.4-1.4-.9-2-.7-.8-2-1.3-3.8-1.3-1.3 0-2.2.3-2.8.8-.7.4-1 1-1 1.8 0 .9.4 1.5 1.3 2 .4.3 1.2.6 2.1.8l2.1.6c2.4.5 4 1 4.7 1.6 1.3.8 2 2.1 2 4a6 6 0 01-2 4.4c-1.3 1.2-3.3 1.9-6 1.9-2.9 0-5-.7-6.1-2a7.4 7.4 0 01-2-4.9h3.2z"/></g></svg>
\ No newline at end of file diff --git a/date-fns/docs/timeZones.md b/date-fns/docs/timeZones.md new file mode 100644 index 0000000..54eb90b --- /dev/null +++ b/date-fns/docs/timeZones.md @@ -0,0 +1,63 @@ +# Time Zones + +## Table of Contents + +- [Overview](#overview) + +- [`date-fns-tz`](#date-fns-tz) + +## Overview + +Working with UTC or ISO date strings is easy, and so is working with JS dates when all times +are displayed in a user's local time in the browser. The difficulty comes when working with another +time zone's local time, other than the current system's, like showing the local time of an event in LA +at 8pm PST on a Node server in Europe or a user's machine set to EST. + +In this case there are two relevant pieces of information: + +- a fixed moment in time in the form of a timestamp, UTC or ISO date string, and +- the time zone descriptor, usually an offset or IANA time zone name (e.g. `America/Los_Angeles`). + +Libraries like Moment and Luxon, which provide their own date time classes, manage these timestamp and time +zone values internally. Since `date-fns` always returns a plain JS Date, which implicitly has the current +system's time zone, helper functions are needed for handling common time zone related use cases. + +## [`date-fns-tz`](https://www.npmjs.com/package/date-fns-tz) + +Dependency free IANA time zone support is implemented via the +[Intl API](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl) to keep +actual time zone data out of code bundles. Modern browsers all support the +[necessary features](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat#Browser_compatibility), +and for those that don't a [polyfill](https://github.com/yahoo/date-time-format-timezone) can be used. + +Functions are provided for converting to and from a Date instance which will have the internal UTC time +adjusted so it prints to the correct time value in the associated time zone, regardless of the current +system time zone. The `date-fns` `format` function is extended with support for the `z...zzzz` tokens to +format long and short time zone names. + +Compatible with `date-fns` version 2 + +License: MIT + +### Synopsis + +```js +const { zonedTimeToUtc, utcToZonedTime, format } = require('date-fns-tz') + +// Set the date to "2018-09-01T16:01:36.386Z" +const utcDate = zonedTimeToUtc('2018-09-01 18:01:36.386', 'Europe/Berlin') + +// Obtain a Date instance that will render the equivalent Berlin time for the UTC date +const date = new Date('2018-09-01T16:01:36.386Z') +const timeZone = 'Europe/Berlin' +const zonedDate = utcToZonedTime(date, timeZone) +// zonedDate could be used to initialize a date picker or display the formatted local date/time + +// Set the output to "1.9.2018 18:01:36.386 GMT+02:00 (CEST)" +const pattern = 'd.M.yyyy HH:mm:ss.SSS \'GMT\' XXX (z)' +const output = format(zonedDate, pattern, { timeZone: 'Europe/Berlin' }) +``` + +### Links + +- [API / Usage Scenarios](https://github.com/marnusw/date-fns-tz#time-zone-helpers) diff --git a/date-fns/docs/unicodeTokens.md b/date-fns/docs/unicodeTokens.md new file mode 100644 index 0000000..5daf282 --- /dev/null +++ b/date-fns/docs/unicodeTokens.md @@ -0,0 +1,54 @@ +# Unicode Tokens + +Starting with v2, `format` and `parse` use [Unicode tokens]. + +The tokens are different from Moment.js and other libraries that opted to use +custom formatting rules. While usage of a standard ensures compatibility and +the future of the library, it causes confusion that this document intends +to resolve. + +## Popular mistakes + +There are 4 tokens that cause most of the confusion: + +- `D` and `DD` that represent the day of a year (1, 2, ..., 365, 366) + are often confused with `d` and `dd` that represent the day of a month + (1, 2, ..., 31). + +- `YY` and `YYYY` that represent the local week-numbering year (44, 01, 00, 17) + are often confused with `yy` and `yyyy` that represent the calendar year. + +```js +// ❌ Wrong! +format(new Date(), 'YYYY-MM-DD') +//=> 2018-10-283 + +// ✅ Correct +format(new Date(), 'yyyy-MM-dd') +//=> 2018-10-10 + +// ❌ Wrong! +parse('11.02.87', 'D.MM.YY', new Date()).toString() +//=> 'Sat Jan 11 1986 00:00:00 GMT+0200 (EET)' + +// ✅ Correct +parse('11.02.87', 'd.MM.yy', new Date()).toString() +//=> 'Wed Feb 11 1987 00:00:00 GMT+0200 (EET)' +``` + +To help with the issue, `format` and `parse` functions won't accept +these tokens without `useAdditionalDayOfYearTokens` option for `D` and `DD` and +`useAdditionalWeekYearTokens` options for `YY` and `YYYY`: + +```js +format(new Date(), 'D', { useAdditionalDayOfYearTokens: true }) +//=> '283' + +parse('365+1987', 'DD+YYYY', new Date(), { + useAdditionalDayOfYearTokens: true, + useAdditionalWeekYearTokens: true +}).toString() +//=> 'Wed Dec 31 1986 00:00:00 GMT+0200 (EET)' +``` + +[Unicode tokens]: https://www.unicode.org/reports/tr35/tr35-dates.html#Date_Field_Symbol_Table diff --git a/date-fns/docs/upgradeGuide.md b/date-fns/docs/upgradeGuide.md new file mode 100644 index 0000000..4f058b4 --- /dev/null +++ b/date-fns/docs/upgradeGuide.md @@ -0,0 +1,118 @@ +# v2 Upgrade Guide + +## Common changes + +This page covers a few of the most common problems people face when updating from v1 to v2. For a more detailed list of changes, look at the [change log for version 2.0.0](https://date-fns.org/docs/Change-Log#2.0.0-2019-08-20). + +### Camel case naming schema + +Function submodules now use camelCase naming schema: + +```javascript +// Before v2.0.0 +import differenceInCalendarISOYears from 'date-fns/difference_in_calendar_iso_years' + +// v2.0.0 onward +import differenceInCalendarISOYears from 'date-fns/differenceInCalendarISOYears' +``` + +### New formatting tokens + +Starting with v2 `format` and `parse` uses [Unicode tokens]. + +See [Unicode Tokens doc](https://date-fns.org/docs/Unicode-Tokens) for more details. + +### String arguments + +Functions now don't accept strings as date arguments. Strings should +be parsed using `parseISO` (ISO 8601) or `parse`. + +See [this post](https://blog.date-fns.org/post/we-cut-date-fns-v2-minimal-build-size-down-to-300-bytes-and-now-its-the-smallest-date-library-18f2nvh2z0yal) for more details. + +```javascript +// Before v2.0.0 +addDays('2016-01-01', 1) + +// v2.0.0 onward +addDays(parseISO('2016-01-01'), 1) +``` + +### Arguments conversion + +All functions now implicitly convert arguments by following rules: + +| | date | number | string | boolean | +| --------- | ------------ | ------ | ----------- | ------- | +| 0 | new Date(0) | 0 | '0' | false | +| '0' | Invalid Date | 0 | '0' | false | +| 1 | new Date(1) | 1 | '1' | true | +| '1' | Invalid Date | 1 | '1' | true | +| true | Invalid Date | NaN | 'true' | true | +| false | Invalid Date | NaN | 'false' | false | +| null | Invalid Date | NaN | 'null' | false | +| undefined | Invalid Date | NaN | 'undefined' | false | +| NaN | Invalid Date | NaN | 'NaN' | false | + +Notes: + +- as before, arguments expected to be `Date` are converted to `Date` using _date-fns'_ `toDate` function; +- arguments expected to be numbers are converted to integer numbers using our custom `toInteger` implementation + (see [#765](https://github.com/date-fns/date-fns/pull/765)); +- arguments expected to be strings are converted to strings using JavaScript's `String` function; +- arguments expected to be booleans are converted to boolean using JavaScript's `Boolean` function. + +`null` and `undefined` passed to optional arguments (i.e. properties of `options` argument) +are ignored as if no argument was passed. + +If any argument is invalid (i.e. `NaN` for numbers and `Invalid Date` for dates), +an invalid value will be returned: + +- `false` for functions that return booleans (expect `isValid`); +- `Invalid Date` for functions that return dates; +- `NaN` for functions that return numbers; +- and `String('Invalid Date')` for functions that return strings. + +See tests and PRs [#460](https://github.com/date-fns/date-fns/pull/460) and +[#765](https://github.com/date-fns/date-fns/pull/765) for exact behavior. + +### `null` + +`null` now is not a valid date. `isValid(null)` returns `false`; +`toDate(null)` returns an invalid date. Since `toDate` is used internally +by all the functions, operations over `null` will also return an invalid date. +[See #537](https://github.com/date-fns/date-fns/issues/537) for the reasoning. + +### `RangeError` + +Functions now throw `RangeError` if optional values passed to `options` +are not `undefined` or have expected values. +This change is introduced for consistency with ECMAScript standard library which does the same. + +### `TypeError` + +All functions now check if the passed number of arguments is less +than the number of required arguments and throw `TypeError` exception if so. + +### UMD/CDN + +The Bower & UMD/CDN package versions are no longer supported. + +### New locale format + +See [docs/Locale](https://date-fns.org/docs/Locale). + +Locales renamed: + +- `en` → `en-US` +- `zh_cn` → `zh-CN` +- `zh_tw` → `zh-TW` + +```javascript +// Before v2.0.0 +import locale from 'date-fns/locale/zh_cn' + +// v2.0.0 onward +import locale from 'date-fns/locale/zh-CN' +``` + +[unicode tokens]: https://www.unicode.org/reports/tr35/tr35-dates.html#Date_Field_Symbol_Table diff --git a/date-fns/docs/webpack.md b/date-fns/docs/webpack.md new file mode 100644 index 0000000..9eb1c10 --- /dev/null +++ b/date-fns/docs/webpack.md @@ -0,0 +1,48 @@ +# webpack + +## Removing unused languages from dynamic import + +If a locale is imported dynamically, then all locales from date-fns are loaded by webpack into a bundle (~160kb) or split across the chunks. This prolongs the build process and increases the amount of space taken. However, it is possible to use webpack to trim down languages using [ContextReplacementPlugin]. + +Let's assume that we have a single point in which supported locales are present: + +`config.js`: + +```js +// `see date-fns/src/locale` for available locales +export const supportedLocales = ['en-US', 'de', 'pl', 'it'] +``` + +We could also have a function that formats the date: + +```js +const getLocale = (locale) => import(`date-fns/locale/${locale}/index.js`) // or require() if using CommonJS + +const formatDate = (date, formatStyle, locale) => { + return format(date, formatStyle, { + locale: getLocale(locale), + }) +} +``` + +In order to exclude unused languages we can use webpacks [ContextReplacementPlugin]. + +`webpack.config.js`: + +```js +import webpack from 'webpack' +import { supportedLocales } from './config.js' + +export default const config = { + plugins: [ + new webpack.ContextReplacementPlugin( + /date\-fns[\/\\]/, + new RegExp(`[/\\\\\](${supportedLocales.join('|')})[/\\\\\]index\.js$`) + ) + ] +} +``` + +This results in a language bundle of ~23kb . + +[contextreplacementplugin]: https://webpack.js.org/plugins/context-replacement-plugin/ |