# i18n

URL: https://caijiao.org/date-fns/general/i18n
Source: docs/date-fns/general/i18n.md
Description: 只有几个函数支持 I18n：format, formatDistance, formatDistanceStrict, formatRelative, 要使用语言环境，您需要使用它，然后将其作为选项传递给函数

## 使用

只有几个函数支持 I18n：

- format

- formatDistance

- formatDistanceStrict

- formatRelative

要使用语言环境，您需要使用它，然后将其作为选项传递给函数：

```javascript
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'
```

要求和传递语言环境作为选项似乎很复杂，但与 Moment.js 不同，默认情况下使用所有语言环境来膨胀你的构建 date-fns 迫使开发人员在需要时手动要求语言环境。 为了使 API 变得简单，我们鼓励您编写小型包装器并使用它们而不是原始函数：

```javascript
// 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
```

## 添加新语言

目前没有明确的指南，所以如果你足够勇敢，请使用这个快速指南：

- 首先，[创建一个问题](https://github.com/date-fns/date-fns/issues/new?title=XXX%20language%20support)，这样您就不会与其他人重叠。

- 关于如何添加[新语言环境](https://github.com/date-fns/date-fns/blob/master/docs/i18nContributionGuide.md#adding-a-new-locale)的详细说明。

- 使用[英语语言](https://github.com/date-fns/date-fns/tree/master/src/locale/en-US)环境作为基础，然后逐步调整测试和代码。

- 关于[添加与另一个语言环境具有相同语言的语言环境](https://github.com/date-fns/date-fns/blob/master/docs/i18nContributionGuide.md#creating-a-locale-with-the-same-language-as-another-locale)的说明。

- 如果您有任何问题或需要指导，请在问题中发表评论。

谢谢您的支持！
