插件是一个独立的模块,可以添加到Day.js来扩展功能或添加新特性。

默认情况下,Day.js只提供核心代码,没有安装插件。

您可以根据需要加载多个插件。

自定义

您可以构建自己的Day.js插件来满足不同的需求。

请随意打开一个pull request来共享你的插件。

Day.js插件的模板。

export default (option, dayjsClass, dayjsFactory) => {
  // extend dayjs()
  // e.g. add dayjs().isSameOrBefore()
  dayjsClass.prototype.isSameOrBefore = function(arguments) {}

  // extend dayjs
  // e.g. add dayjs.utc()
  dayjsFactory.utc = arguments => {}

  // overriding existing API
  // e.g. extend dayjs().format()
  const oldFormat = dayjsClass.prototype.format
  dayjsClass.prototype.format = function(arguments) {
    // original format result
    const result = oldFormat.bind(this)(arguments)
    // return modified result
  }
}

# 在NodeJS中加载插件

按需加载插件。

var AdvancedFormat = require('dayjs/plugin/advancedFormat')
// import AdvancedFormat from 'dayjs/plugin/advancedFormat' // ES 2015

dayjs.extend(AdvancedFormat) // use plugin

注意

文档中的插件数量可能与实际下载在 node_modules/dayjs/plugin/ 中的插件数量不一至,使用的时候注意对照一下。

# 在浏览器中加载插件

按需加载插件。

<script src="path/to/dayjs/plugin/advancedFormat"></script>
<!-- Load plugin as window.dayjs_plugin_NAME -->
<script>
  dayjs.extend(window.dayjs_plugin_advancedFormat)
</script>

Day.js可在CDN上使用。

<!-- CDN example (unpkg) -->
<script src="https://unpkg.com/dayjs@1.8.21/dayjs.min.js"></script>
<script src="https://unpkg.com/dayjs@1.8.21/plugin/utc.js"></script>
<script>dayjs.extend(window.dayjs_plugin_utc)</script>

TIP

其他插件:依照官方插件名称使用 https://unpkg.com/dayjs{插件版本(可选)}/plugin/{插件名称}.js 方式找,如:https://unpkg.com/dayjs@1.8.21/plugin/calendar.js
其他类库:https://unpkg.com/{类库名称},如:https://unpkg.com/mock

# 插件列表

官方插件目录:https://github.com/iamkun/dayjs/tree/dev/src/plugin (opens new window)

# AdvancedFormat

AdvancedFormat延伸dayjs()。格式化API以提供更多的格式选项。

var advancedFormat = require('dayjs/plugin/advancedFormat')
dayjs.extend(advancedFormat)

dayjs().format('Q Do k kk X x')

已有的格式列表:

格式 输出 描述
Q 1-4 季度
Do 1st 2nd ... 31st 月份的日期与序号
k 1-24 整点,1点开始
kk 01-24 小时,2位数,从1开始
X 1360013296 Unix时间戳为秒
x 1360013296123 Unix时间戳(毫秒)
w 1 2 ... 52 53 年周(依赖于 WeekOfYear 插件)
ww 01 02 ... 52 53 年份的周数,2位数(依赖于 WeekOfYear 插件)
wo 1st 2nd ... 52nd 53rd 带序号的年份周(依赖于 WeekOfYear 插件)
gggg 2017 周年(依赖于 WeekYear 插件)

# ArraySupport

ArraySupport 扩展了 dayjs(), dayjs.utc API 以支持数组参数。

var arraySupport = require("dayjs/plugin/arraySupport");
dayjs.extend(arraySupport);

dayjs([2010, 1, 14, 15, 25, 50, 125]);
dayjs.utc([2010, 1, 14, 15, 25, 50, 125]);

# BadMutable

Day.js 被设计成不可变的对象,但是为了方便一些老项目实现对 moment.js 的替换,可以使用🚨 BadMutable 🚨插件让 Day.js 转变成可变的对象,

注意

这并不好,也不推荐在大多数项目中使用。

当使用这个插件后,所有的 setter 都会更新当前实例。

var badMutable = require('dayjs/plugin/badMutable')
dayjs.extend(badMutable)
// with 🚨 BadMutable 🚨 plugin
const today = dayjs()
today.add(1, 'day')
console.log(today) // update itself, value will be tomorrow

# BuddhistEra

BuddhistEra 扩展了 dayjs().format API 以支持佛历格式化。

佛历是一个年份编号系统,主要用于柬埔寨、老挝、缅甸和泰国等东南亚国家以及斯里兰卡、马来西亚和新加坡的中国人,用于宗教或官方场合 (Wikipedia)。

要计算 BE 年,只需在年份中添加 543。 例如,1977 年 5 月 26 日 AD / CE 应显示为 2520 年 5 月 26 日 BE(1977 + 543)。

var buddhistEra = require('dayjs/plugin/buddhistEra')
dayjs.extend(buddhistEra)

dayjs().format('BBBB BB')

扩展的模版列表:

格式 输出 描述
BBBB 2561 完整佛历年 (年份 + 543)
BB 61 佛历年 (年份 + 543) 两位数

# Calendar

Calendar 增加了 .calendar API 返回一个 string 来显示日历时间。

var calendar = require('dayjs/plugin/calendar')
dayjs.extend(calendar)

dayjs().calendar(dayjs('2008-01-01'))
dayjs().calendar(null, {
  sameDay: '[Today at] h:mm A', // The same day ( Today at 2:30 AM )
  nextDay: '[Tomorrow]', // The next day ( Tomorrow at 2:30 AM )
  nextWeek: 'dddd', // The next week ( Sunday at 2:30 AM )
  lastDay: '[Yesterday]', // The day before ( Yesterday at 2:30 AM )
  lastWeek: '[Last] dddd', // Last week ( Last Monday at 2:30 AM )
  sameElse: 'DD/MM/YYYY' // Everything else ( 7/10/2011 )
})

# CustomParseFormat

CustomParseFormat 拓展了 dayjs() 支持自定义时间格式。

var customParseFormat = require('dayjs/plugin/customParseFormat')
dayjs.extend(customParseFormat)

dayjs('05/02/69 1:02:03 PM -05:00', 'MM/DD/YY H:mm:ss A Z')
// Returns an instance containing '1969-05-02T18:02:03.000Z'

dayjs('2018 Enero 15', 'YYYY MMMM DD', 'es')
// Returns an instance containing '2018-01-15T00:00:00.000Z'

dayjs('1970-00-00', 'YYYY-MM-DD', true) // strict parsing

支持的解析占位符列表:

输入 示例 描述
YY 18 两位数的年份
YYYY 2018 四位数的年份
M 1-12 月份,从 1 开始
MM 01-12 月份,两位数
MMM Jan-Dec 缩写的月份名称
MMMM January-December 完整的月份名称
D 1-31 月份里的一天
DD 01-31 月份里的一天,两位数
H 0-23 小时
HH 00-23 小时,两位数
h 1-12 小时, 12 小时制
hh 01-12 小时, 12 小时制, 两位数
m 0-59 分钟
mm 00-59 分钟,两位数
s 0-59
ss 00-59 秒,两位数
S 0-9 毫秒,一位数
SS 00-99 毫秒,两位数
SSS 000-999 毫秒,三位数
Z -05:00 UTC 的偏移量
ZZ -0500 UTC 的偏移量,两位数
A AM / PM 上午 下午 大写
a am / pm 上午 下午 小写
Do 1st... 31st 带序数词的月份里的一天
X 1410715640.579 Unix 时间戳
x 1410715640579 Unix 时间戳

# DayOfYear

DayOfYear 增加了 .dayOfYear() API 返回一个 number 来表示 Dayjs 的日期是年中第几天,或设置成是年中第几天。

var dayOfYear = require('dayjs/plugin/dayOfYear')
dayjs.extend(dayOfYear)

dayjs('2010-01-01').dayOfYear() // 1
dayjs('2010-01-01').dayOfYear(365) // 2010-12-31

# DevHelper

DevHelper 可以在您使用 Day.js 时显示一些提示和警告方便开发。

注意,您可以将 process.env.NODE_ENV 设置为 production 以禁用您的生产环境中的DevHelper。 如果您启用了像UglifyJS这样的 JavaScript 优化工具,它可以自动从生产包中移除此插件来减小打包体积。

var devHelper = require('dayjs/plugin/devHelper')

dayjs.extend(devHelper)

您也可自行实现按需加载此插件。

if (isInDevelopment) {
  // load DevHelper plugin like above
}

# Duration

Duration 增加了 .duration .isDuring API 来支持时间长度。

var duration = require('dayjs/plugin/duration')
dayjs.extend(duration)

dayjs.duration(100)

# IsBetween

IsBetween 增加了 .isBetween() API 返回一个 boolean 来展示一个时间是否介于两个时间之间。

var isBetween = require('dayjs/plugin/isBetween')
dayjs.extend(isBetween)

// 如果使用年份对比 `year` 则传入第三个参数
dayjs('2010-10-20').isBetween('2010-10-19', dayjs('2010-10-25'), 'year')

// 第四个参数是两个字符 '[' 表示包含, '(' 表示不包含
// '()' 不包含开始和结束的日期 (默认)
// '[]' 包含开始和结束的日期
// '[)' 包含开始日期但不包含结束日期
// 例如,当想包含开始的日期作为比较依据,你应该使用“day”作为第三个参数。
dayjs('2016-10-30').isBetween('2016-01-01', '2016-10-30', 'day', '[)')

# IsLeapYear

IsLeapYear 增加了 .isLeapYear API 返回一个 boolean 来展示一个 Day.js 对象的年份是不是闰年。

var isLeapYear = require('dayjs/plugin/isLeapYear')
dayjs.extend(isLeapYear)

dayjs('2000-01-01').isLeapYear() // true

# IsSameOrAfter

IsSameOrAfter 增加了 .isSameOrAfter() API 返回一个 boolean 来展示一个时间是否和一个时间相同或在一个时间之后。

var isSameOrAfter = require('dayjs/plugin/isSameOrAfter')
dayjs.extend(isSameOrAfter)

dayjs('2010-10-20').isSameOrAfter('2010-10-19', 'year')

# IsSameOrBefore

IsSameOrBefore 增加了 .isSameOrBefore() API 返回一个 boolean 来展示一个时间是否和一个时间相同或在一个时间之前。

var isSameOrBefore = require('dayjs/plugin/isSameOrBefore')
dayjs.extend(isSameOrBefore)

dayjs('2010-10-20').isSameOrBefore('2010-10-19', 'year')

# IsToday

IsToday 增加了 .isToday() API 来判断当前 Day.js 对象是否是今天。

var isToday = require('dayjs/plugin/isToday')

dayjs.extend(isToday)

dayjs().isToday() // true

# IsTomorrow

IsTomorrow 增加了 .isTomorrow() API 来判断当前 Day.js 对象是否是明天。

var isTomorrow = require('dayjs/plugin/isTomorrow')

dayjs.extend(isTomorrow)

dayjs().add(1, 'day').isTomorrow() // true

# IsYesterday

IsYesterday 增加了 .isYesterday() API 来判断当前 Day.js 对象是否是昨天。

var isYesterday = require('dayjs/plugin/isYesterday')

dayjs.extend(isYesterday)

dayjs().add(-1, 'day').isYesterday() // true

# IsoWeek

IsoWeek 添加 .isoWeek() API 以获取或设置年度的 ISO 周数。 并添加 .isoWeekday() 获取或设置一周的 ISO 日和 isoWeekYear() 获取ISO 周年,并扩展 .startOf .endOf APIs 支持单位 isoWeek

var isoWeek = require('dayjs/plugin/isoWeek')

dayjs.extend(isoWeek)

dayjs().isoWeek()
dayjs().isoWeekday()
dayjs().isoWeekYear()

# IsoWeeksInYear

IsoWeeksInYear 增加了 .isoWeeksInYear() API 返回一个 number 来得到依据 ISO week 标准一年中有几周

注意

此功能依赖 IsLeapYear 插件,才能正常运行

var isoWeeksInYear = require('dayjs/plugin/isoWeeksInYear')
var isLeapYear = require('dayjs/plugin/isLeapYear') // dependent on isLeapYear plugin
dayjs.extend(isoWeeksInYear)
dayjs.extend(isLeapYear)

dayjs('2004-01-01').isoWeeksInYear() // 53
dayjs('2005-01-01').isoWeeksInYear() // 52

# LocaleData

LocaleData 增加了 dayjs().localeData API 来提供本地化数据。

var localeData = require('dayjs/plugin/localeData')
dayjs.extend(localeData)

dayjs().localeData()

支持的方法:

dayjs.months()
dayjs.monthsShort()
dayjs.weekdays()
dayjs.weekdaysShort()
dayjs.weekdaysMin()
dayjs.longDateFormat('L')

globalLocaleData = dayjs.localeData()
globalLocaleData.firstDayOfWeek()
globalLocaleData.months()
globalLocaleData.monthsShort()
globalLocaleData.weekdays()
globalLocaleData.weekdaysShort()
globalLocaleData.weekdaysMin()
globalLocaleData.longDateFormat('L')

globalLocaleData.months(dayjs())
globalLocaleData.monthsShort(dayjs())
globalLocaleData.weekdays(dayjs())
globalLocaleData.weekdaysShort(dayjs())
globalLocaleData.weekdaysMin(dayjs())
globalLocaleData.meridiem()
globalLocaleData.ordinal()

instanceLocaleData = dayjs().localeData()
instanceLocaleData.firstDayOfWeek()
instanceLocaleData.months()
instanceLocaleData.monthsShort()
instanceLocaleData.weekdays()
instanceLocaleData.weekdaysShort()
instanceLocaleData.weekdaysMin()
instanceLocaleData.longDateFormat('L')
instanceLocaleData.meridiem()
instanceLocaleData.ordinal()

# LocalizedFormat

LocalizedFormat 扩展了 dayjs().format API 以支持更多本地化的长日期格式。

var localizedFormat = require('dayjs/plugin/localizedFormat')
dayjs.extend(localizedFormat)

dayjs().format('L LT')

支持的本地化格式列表

# MinMax

MinMax 增加了 .min .maxAPI 返回一个 dayjs 来比较传入的 Day.js 实例的大小。 它接受传入多个 Day.js实例或一个数组。

var minMax = require('dayjs/plugin/minMax')
dayjs.extend(minMax)

dayjs.max(dayjs(), dayjs('2018-01-01'), dayjs('2019-01-01'))
dayjs.min([dayjs(), dayjs('2018-01-01'), dayjs('2019-01-01')])

# ObjectSupport

ObjectSupport 扩展了 dayjs(), dayjs.utc, dayjs().set, dayjs().add, dayjs().subtract API 以支持传入对象参数。

var objectSupport = require("dayjs/plugin/objectSupport");
dayjs.extend(objectSupport);

dayjs({
  year: 2010,
  month: 1,
  day: 12
});
dayjs.utc({
  year: 2010,
  month: 1,
  day: 12
});
dayjs().set({ year: 2010, month: 1, day: 12 })
dayjs().add({ M: 1 })
dayjs().subtract({ month: 1 })

# PluralGetSet

PluralGetSet 增加了复数形式的 API .milliseconds(), .seconds(), .minutes(), .hours(), .days(), .weeks(), .isoWeeks(), .months(), .quarters(), .years(), .dates()

var pluralGetSet = require('dayjs/plugin/pluralGetSet')
dayjs.extend(pluralGetSet)

dayjs().millisecond()
dayjs().milliseconds()

# PreParsePostFormat

预解析/后格式化让您在解析前处理输入,并在格式化要输出的字符串。 参考类似 moment.js (opens new window) 国际化里的用法。

注意

此插件需要在 localeData 插件之前导入(因为有依赖关系)。

注意

此插件也会改变 relativeTime 插件的相关行为

# 基础用法

例如: 在阿拉伯语言中,它被用于支持阿拉伯数字的特殊显示 (opens new window)

// Arabic [ar]
import dayjs from 'dayjs'
import preParsePostFormat from 'dayjs/plugin/preParsePostFormat'
dayjs.extend(preParsePostFormat)

const months = 'يناير_فبراير_مارس_أبريل_مايو_يونيو_يوليو_أغسطس_سبتمبر_أكتوبر_نوفمبر_ديسمبر'.split('_')
const symbolMap = {
  1: '١',
  2: '٢',
  3: '٣',
  4: '٤',
  5: '٥',
  6: '٦',
  7: '٧',
  8: '٨',
  9: '٩',
  0: '٠'
}

const numberMap = {
  '١': '1',
  '٢': '2',
  '٣': '3',
  '٤': '4',
  '٥': '5',
  '٦': '6',
  '٧': '7',
  '٨': '8',
  '٩': '9',
  '٠': '0'
}

const locale = {
  name: 'ar',
  // ...
  preparse(string) {
    return string
      .replace(
        /[١٢٣٤٥٦٧٨٩٠]/g,
        match => numberMap[match]
      )
      .replace(/،/g, ',')
  },
  postformat(string) {
    return string
      .replace(/\d/g, match => symbolMap[match])
      .replace(/,/g, '،')
  },
  // ...
}
// ...

单元测试 (opens new window) 也应该让您很好地了解如何使用插件。

# QuarterOfYear

QuarterOfYear 增加了 .quarter() API 返回当前实例是哪个季度,并扩展了 .add .subtract .startOf .endOf API 来支持 quarter 季度单位。

var quarterOfYear = require('dayjs/plugin/quarterOfYear')
dayjs.extend(quarterOfYear)

dayjs('2010-04-01').quarter() // 2
dayjs('2010-04-01').quarter(2)

# RelativeTime

RelativeTime 增加了 .from .to .fromNow .toNow 4 个 API 来展示相对的时间 (例如:3 小时以前)。

var relativeTime = require('dayjs/plugin/relativeTime')
dayjs.extend(relativeTime)

dayjs().from(dayjs('1990-01-01')) // 31 年后
dayjs().from(dayjs('1990-01-01'), true) // 31 年
dayjs().fromNow()

dayjs().to(dayjs('1990-01-01')) // 31 年前
dayjs().toNow()

# 距离现在的相对时间 .fromNow(withoutSuffix?: boolean)

返回 string 距离现在的相对时间

# 距离 X 的相对时间 .from(compared: Dayjs, withoutSuffix?: boolean)

返回 string 距离 X 的相对时间

# 到现在的相对时间 .toNow(withoutSuffix?: boolean)

返回 string 到现在的相对时间

# 到 X 的相对时间 .to(compared: Dayjs, withoutSuffix?: boolean)

返回 string 到 X 的相对时间

时间范围划分标准:

范围 键值 示例输出
0 到 44 秒 s 几秒前
45 到 89 秒 m 1 分钟前
90 秒 到 44 分 mm 2 分钟前 ... 44 分钟前
45 到 89 分 h 1 小时前
90 分 到 21 小时 hh 2 小时前 ... 21 小时前
22 到 35 小时 d 1 天前
36 小时 到 25 天 dd 2 天前 ... 25 天前
26 到 45 天 M 1 个月前
46 天 到 10 月 MM 2 个月前 ... 10 个月前
11 月 到 17 月 y 1 年前
18 月以上 yy 2 年前 ... 20 年前

# Timezone

Timezone 插件添加了 dayjs.tz .tz .tz.guess .tz.setDefault API,在时区之间解析或显示。

var utc = require('dayjs/plugin/utc')
var timezone = require('dayjs/plugin/timezone') // dependent on utc plugin
dayjs.extend(utc)
dayjs.extend(timezone)

dayjs.tz("2014-06-01 12:00", "America/New_York")

dayjs("2014-06-01 12:00").tz("America/New_York")

dayjs.tz.guess()

dayjs.tz.setDefault("America/New_York")

# ToArray

ToArray 增加了 .toArray() API 来返回包含时间数值的 array。

var toArray = require('dayjs/plugin/toArray')
dayjs.extend(toArray)

dayjs('2019-01-25').toArray() // [ 2019, 0, 25, 0, 0, 0, 0 ]

# ToObject

ToObject 增加了 .toObject() API 来返回包含时间数值的 object

var toObject = require('dayjs/plugin/toObject')
dayjs.extend(toObject)

dayjs('2019-01-25').toObject()
/* { years: 2019,
     months: 0,
     date: 25,
     hours: 0,
     minutes: 0,
     seconds: 0,
     milliseconds: 0 } */

# UpdateLocale

UpdateLocale 增加了 .updateLocale API 来更新语言配置的属性。

var updateLocale = require('dayjs/plugin/updateLocale')
dayjs.extend(updateLocale)

dayjs.updateLocale('en', {
  months : String[]
})

# UTC

UTC 增加了 .utc .local .isUTC APIs 使用 UTC 模式来解析和展示时间。

var utc = require('dayjs/plugin/utc')
dayjs.extend(utc)

// 默认当地时间
dayjs().format() //2019-03-06T17:11:55+08:00

// UTC 模式
dayjs.utc().format() // 2019-03-06T09:11:55Z

// 将本地时间转换成 UTC 时间
dayjs().utc().format() // 2019-03-06T09:11:55Z 

// 在 UTC 模式下,所有的展示方法都将使用 UTC 而不是本地时区
// 所有的 get 和 set 方法也都会使用 Date#getUTC* 和 Date#setUTC* 而不是 Date#get* and Date#set*
dayjs.utc().isUTC() // true
dayjs.utc().local().format() //2019-03-06T17:11:55+08:00
dayjs.utc('2018-01-01', 'YYYY-MM-DD') // with CustomParseFormat plugin

默认情况下,Day.js 会把时间解析成本地时间。

Day.js 默认使用用户本地时区来解析和展示时间。 如果想要使用 UTC 模式来解析和展示时间,可以使用 dayjs.utc() 而不是 dayjs()

# dayjs.utc dayjs.utc(dateType?: string | number | Date | Dayjs, format? string)

返回一个使用 UTC 模式的 Dayjs 对象。

# Use UTC time .utc()

返回一个复制的包含使用 UTC 模式标记的 Dayjs 对象。

# Use local time .local()

返回一个复制的包含使用本地时区标记的 Dayjs 对象。

# Set UTC offset .utcOffset()

返回一个复制的使用 UTC 模式的 Day.js 对象。

# isUTC mode .isUTC()

返回一个 boolean 来展示当前 Day.js 对象是不是在 UTC 模式下。

# Weekday

WeekDay 增加了 .weekday() API 来获取或设置当前语言的星期。

var weekday = require('dayjs/plugin/weekday')
dayjs.extend(weekday)

// 当星期天是一周的第一天
dayjs().weekday(-7); // 上个星期天
dayjs().weekday(7); // 下个星期天

// 当星期一是一周的第一天
dayjs().weekday(-7) // 上个星期一
dayjs().weekday(7) // 下个星期一

# weekOfYear

WeekOfYear 增加了 .week() API 返回一个 number 来表示 Day.js 的日期是年中第几周。

var weekOfYear = require('dayjs/plugin/weekOfYear')
dayjs.extend(weekOfYear)

dayjs('2018-06-27').week() // 26
dayjs('2018-06-27').week(5) // 设置周

# WeekYear

WeekYear 增加了 .weekYear() API 来获取基于当前语言的按周计算的年份。

var weekYear = require('dayjs/plugin/weekYear') // dependent on weekOfYear plugin
var weekOfYear = require('dayjs/plugin/weekOfYear')
dayjs.extend(weekOfYear)
dayjs.extend(weekYear)

dayjs().weekYear()
Last Updated: 1/6/2023, 3:16:09 PM