教程 date-fns tutorial

i18n

使用

只有几个函数支持 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

添加新语言

目前没有明确的指南,所以如果你足够勇敢,请使用这个快速指南:

谢谢您的支持!