Skip to content

Latest commit

 

History

History
114 lines (86 loc) · 3.15 KB

I18n.md

File metadata and controls

114 lines (86 loc) · 3.15 KB

国际化 I18n

Day.js 支持国际化

但除非手动加载,多国语言默认是不会被打包到工程里的

Day.js 内置的是英语(English - United States)语言

您可以加载多个其他语言并自由切换

支持的语言列表

欢迎给我们提交 Pull Request 来增加新的语言

API

改变全局语言

  • 返回使用语言的字符串
import 'dayjs/locale/zh-cn'
import de from 'dayjs/locale/de'
dayjs.locale('zh-cn') // 全局使用简体中文
dayjs.locale('de-german', de) // 使用并更新语言包的名字
const customizedLocaleObject = { ... } // 更多细节请参考下方的自定义语言对象
dayjs.locale(customizedLocaleObject) // 使用自定义语言
dayjs.locale('en') // 全局使用默认的英语语言
  • 改变全局语言并不会影响在此之前生成的实例

改变当前实例的语言

  • 改变语言并返回新的Dayjs 对象

用法与dayjs#locale一致, 但只影响当前实例的语言设置

import 'dayjs/locale/es'
dayjs().locale('es').format() // 局部修改语言配置
dayjs('2018-4-28', { locale: es }) // 在新建实例时指定

安装

  • 通过 NPM:
import 'dayjs/locale/es' // 按需加载
// require('dayjs/locale/es') // CommonJS
// import locale_es from 'dayjs/locale/es' -> 加载并获取 locale_es 配置对象

dayjs.locale('es') // 全局使用
dayjs().locale('es').format() // 当前实例使用
  • 通过 CDN:
<script src="https://unpkg.com/dayjs"></script>
<!-- 通过 window.dayjs_locale_NAME 获取-->
<script src="https://unpkg.com/dayjs/locale/zh-cn"></script>
<script>
  dayjs.locale('zh-cn');
  dayjs().locale('zh-cn').format()
  // 获取语言配置对象
  var customLocale = window.dayjs_locale_zh_cn // zh-cn -> zh_cn
</script>

自定义

你可以根据需要自由的编写一个Day.js语言配置

同时欢迎提交PR与大家分享你的语言配置

Day.js 的语言配置模版

const localeObject = {
  name: 'es', // 语言名 String
  weekdays: 'Domingo_Lunes ...'.split('_'), // 星期 Array
  weekdaysShort: 'Sun_M'.split('_'), // 可选, 短的星期 Array, 如果没提供则使用前三个字符
  weekdaysMin: 'Su_Mo'.split('_'), // 可选, 最短的星期 Array, 如果没提供则使用前两个字符
  months: 'Enero_Febrero ... '.split('_'), // 月份 Array
  monthsShort: 'Jan_F'.split('_'), // 可选, 短的月份 Array, 如果没提供则使用前三个字符
  ordinal: n => `${n}º`, // 序号生成工厂函数 Function (number) => return number + output
  relativeTime: { // 相对时间, %s %d 不用翻译
    future: 'in %s', // e.g. in 2 hours, %s been replaced with 2hours
    past: '%s ago',
    s: 'a few seconds',
    m: 'a minute',
    mm: '%d minutes',
    h: 'an hour',
    hh: '%d hours', // e.g. 2 hours, %d been replaced with 2
    d: 'a day',
    dd: '%d days',
    M: 'a month',
    MM: '%d months',
    y: 'a year',
    yy: '%d years'
  }
}

Day.js 的语言配置本地加载样例

import dayjs from 'dayjs'

const locale = { ... } // 你的 Day.js 语言配置

dayjs.locale(locale, null, true) // 设置配置

export default locale