Day.js 官方插件 API 速查手册(全收录 / 小白友好 / 可直接上手)

0 阅读18分钟

同学们好,我是 Eugene(尤金),一个拥有多年中后台开发经验的前端工程师~

(Eugene 发音很简单,/juːˈdʒiːn/,大家怎么顺口怎么叫就好)

你是否也有过:明明学过很多技术,一到关键时候却讲不出来、甚至写不出来?

你是否也曾怀疑自己,是不是太笨了,明明感觉会,却总差一口气?

就算想沉下心从头梳理,可工作那么忙,回家还要陪伴家人。

一天只有24小时,时间永远不够用,常常感到力不从心。

技术行业,本就是逆水行舟,不进则退。

如果你也有同样的困扰,别慌。

从现在开始,跟着我一起心态归零,利用碎片时间,来一次彻彻底底的基础扫盲

这一次,我们一起慢慢来,扎扎实实变强。

不搞花里胡哨的理论堆砌,只分享看得懂、用得上的前端干货,

咱们一起稳步积累,真正摆脱“面向搜索引擎写代码”的尴尬。

本文收录了 Day.js 全部官方插件的用法速查。不讲废话,每个插件都标明:干什么用的、怎么装、怎么用、注意事项。适合收藏后随时翻阅。

本文基于 Day.js 官方文档整理,如有更新请以 官方文档 为准。

Day.js 安装与插件加载方式

安装 Day.js

# npm
npm install dayjs

# yarn
yarn add dayjs

# pnpm
pnpm add dayjs

CDN 引入

<script src="https://cdn.jsdelivr.net/npm/dayjs@1/dayjs.min.js"></script>
<!-- 按需加载插件,例如 RelativeTime -->
<script src="https://cdn.jsdelivr.net/npm/dayjs@1/plugin/relativeTime.js"></script>

插件加载方式(所有插件通用)

Node.js / 构建工具环境:

import dayjs from 'dayjs'
import 插件名 from 'dayjs/plugin/插件名'

dayjs.extend(插件名)

浏览器 CDN 环境:

<script src="https://cdn.jsdelivr.net/npm/dayjs@1/dayjs.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/dayjs@1/plugin/relativeTime.js"></script>
<script>
  dayjs.extend(window.dayjs_plugin_relativeTime)
</script>

下文每个插件的 import 路径都已标注,不再重复说明加载套路。

一、格式化增强类

1. AdvancedFormat — 扩展格式化选项

路径: dayjs/plugin/advancedFormat

作用:dayjs().format() 的基础上,增加季度、序数日、Unix 时间戳等格式。

import advancedFormat from 'dayjs/plugin/advancedFormat'
dayjs.extend(advancedFormat)

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

新增的格式化 token:

Token输出示例说明
Q1-4季度
Do1st, 2nd, 31st月中第几天(带英文序数)
k1-24小时(从 1 开始)
kk01-24小时 2 位(从 1 开始)
X1360013296Unix 时间戳(秒)
x1360013296123Unix 时间戳(毫秒)
w1-53年中第几周(需 WeekOfYear 插件)
ww01-53年中第几周 2 位(需 WeekOfYear 插件)
W1-53ISO 年中第几周(需 IsoWeek 插件)
WW01-53ISO 年中第几周 2 位(需 IsoWeek 插件)
wo1st-53rd年中第几周带序数(需 WeekOfYear 插件)
gggg2017周年份(需 WeekYear 插件)
GGGG2017ISO 周年份(需 IsoWeek 插件)
zEST时区缩写(需 Timezone 插件)
zzzEastern Standard Time时区全称(需 Timezone 插件)

2. LocalizedFormat — 本地化格式

路径: dayjs/plugin/localizedFormat

作用: 扩展 format() 支持本地化格式(类似 moment.js 的 LLL 等)。

import localizedFormat from 'dayjs/plugin/localizedFormat'
dayjs.extend(localizedFormat)

dayjs().format('L LT')

新增的本地化 token:

Token英文环境输出示例
LTh:mm A8:02 PM
LTSh:mm:ss A8:02:18 PM
LMM/DD/YYYY08/16/2018
LLMMMM D, YYYYAugust 16, 2018
LLLMMMM D, YYYY h:mm AAugust 16, 2018 8:02 PM
LLLLdddd, MMMM D, YYYY h:mm AThursday, August 16, 2018 8:02 PM
lM/D/YYYY8/16/2018
llMMM D, YYYYAug 16, 2018
lllMMM D, YYYY h:mm AAug 16, 2018 8:02 PM
llllddd, MMM D, YYYY h:mm AThu, Aug 16, 2018 8:02 PM

不同 locale 输出不同。使用前需加载对应语言包,如 import 'dayjs/locale/zh-cn'


3. BuddhistEra — 佛历纪年

路径: dayjs/plugin/buddhistEra

作用:format() 中支持佛历年份格式化(年份 + 543)。

import buddhistEra from 'dayjs/plugin/buddhistEra'
dayjs.extend(buddhistEra)

dayjs().format('BBBB BB')
Token输出示例说明
BBBB2561完整佛历年份
BB612 位佛历年份

二、解析增强类

4. CustomParseFormat — 自定义解析格式

路径: dayjs/plugin/customParseFormat

作用: 支持用自定义格式字符串解析日期(类似 moment的解析能力)。

import customParseFormat from 'dayjs/plugin/customParseFormat'
dayjs.extend(customParseFormat)

dayjs('05/02/69 1:02:03 PM -05:00', 'MM/DD/YY H:mm:ss A Z')

// 指定 locale 解析
dayjs('2018 Enero 15', 'YYYY MMMM DD', 'es')

// 严格模式(格式必须完全匹配)
dayjs('1970-00-00', 'YYYY-MM-DD', true).isValid() // false

// 传入格式数组,逐个尝试
dayjs('12-25-2001', ['YYYY', 'YYYY-MM-DD'], 'es', true)

支持的解析 token(完整列表):

Token示例说明
YY01两位年
YYYY2001四位年
M1-12月(从 1 开始)
MM01-12月(2 位)
MMMJan-Dec月缩写
MMMMJanuary-December月全称
D1-31
DD01-31日(2 位)
H0-23时(24 小时制)
HH00-23时(24 小时制 2 位)
h1-12时(12 小时制)
hh01-12时(12 小时制 2 位)
m0-59
mm00-59分(2 位)
s0-59
ss00-59秒(2 位)
S0-9百毫秒(1 位)
SS00-99十毫秒(2 位)
SSS000-999毫秒(3 位)
Z-05:00UTC 偏移量
ZZ-0500UTC 偏移量(紧凑)
AAM / PM上午 / 下午(大写)
aam / pm上午 / 下午(小写)
Do1st-31st日(带序数)
X1410715640.579Unix 时间戳(秒)
x1410715640579Unix 时间戳(毫秒)

5. ArraySupport — 数组参数支持

路径: dayjs/plugin/arraySupport

作用:dayjs()dayjs.utc() 支持数组形式传参。

import arraySupport from 'dayjs/plugin/arraySupport'
dayjs.extend(arraySupport)

dayjs([2010, 1, 14, 15, 25, 50, 125])
// 等同于 new Date(2010, 1, 14, 15, 25, 50, 125)

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

注意:月份从 0 开始(0 = 一月)。


6. ObjectSupport — 对象参数支持

路径: dayjs/plugin/objectSupport

作用:dayjs()dayjs.utc().set().add().subtract() 支持对象参数。

import objectSupport from '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 })

7. BigIntSupport — BigInt 支持

路径: dayjs/plugin/bigIntSupport

作用:dayjs()dayjs.unix() 支持 BigInt 类型参数。

import bigIntSupport from 'dayjs/plugin/bigIntSupport'
dayjs.extend(bigIntSupport)

dayjs(BigInt(1666310421101))
dayjs.unix(BigInt(1666311003))

三、日期判断类

8. IsBetween — 判断是否在两个日期之间

路径: dayjs/plugin/isBetween

作用: 返回布尔值,判断日期是否在两个日期之间。

import isBetween from 'dayjs/plugin/isBetween'
dayjs.extend(isBetween)

dayjs('2010-10-20').isBetween('2010-10-19', '2010-10-25') // true

// 第三个参数:比较粒度(year / month / day 等)
dayjs('2010-10-20').isBetween('2010-10-19', dayjs('2010-10-25'), 'year')

// 第四个参数:边界包含规则
// '()' 默认,不含首尾
// '[]' 包含首尾
// '[)' 包含开始,不含结束
// '(]' 不含开始,包含结束
dayjs('2016-10-30').isBetween('2016-01-01', '2016-10-30', 'day', '[)')

9. IsSameOrAfter — 判断是否相同或之后

路径: dayjs/plugin/isSameOrAfter

import isSameOrAfter from 'dayjs/plugin/isSameOrAfter'
dayjs.extend(isSameOrAfter)

dayjs('2010-10-20').isSameOrAfter('2010-10-19')        // true
dayjs('2010-10-20').isSameOrAfter('2010-10-19', 'year') // true(按年比较)

10. IsSameOrBefore — 判断是否相同或之前

路径: dayjs/plugin/isSameOrBefore

import isSameOrBefore from 'dayjs/plugin/isSameOrBefore'
dayjs.extend(isSameOrBefore)

dayjs('2010-10-20').isSameOrBefore('2010-10-21')        // true
dayjs('2010-10-20').isSameOrBefore('2010-10-19', 'year') // true(按年比较)

11. IsLeapYear — 判断闰年

路径: dayjs/plugin/isLeapYear

import isLeapYear from 'dayjs/plugin/isLeapYear'
dayjs.extend(isLeapYear)

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

12. IsToday — 判断是否是今天

路径: dayjs/plugin/isToday

import isToday from 'dayjs/plugin/isToday'
dayjs.extend(isToday)

dayjs().isToday() // true

13. IsTomorrow — 判断是否是明天

路径: dayjs/plugin/isTomorrow

import isTomorrow from 'dayjs/plugin/isTomorrow'
dayjs.extend(isTomorrow)

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

14. IsYesterday — 判断是否是昨天

路径: dayjs/plugin/isYesterday

import isYesterday from 'dayjs/plugin/isYesterday'
dayjs.extend(isYesterday)

dayjs().subtract(1, 'day').isYesterday() // true

四、相对时间与日历类

15. RelativeTime — 相对时间

路径: dayjs/plugin/relativeTime

作用: 添加 .from() .to() .fromNow() .toNow() 四个 API,用于显示"3 小时前"之类的文字。

import relativeTime from 'dayjs/plugin/relativeTime'
dayjs.extend(relativeTime)

dayjs().from(dayjs('1990-01-01'))        // "in 36 years"
dayjs().from(dayjs('1990-01-01'), true)  // "36 years"(不带前缀后缀)
dayjs().fromNow()                         // "a few seconds ago"

dayjs().to(dayjs('1990-01-01'))          // "36 years ago"
dayjs().toNow()

API 说明:

方法说明
.fromNow(withoutSuffix?)距离现在的相对时间
.from(compared, withoutSuffix?)距离指定时间的相对时间
.toNow(withoutSuffix?)到现在的相对时间
.to(compared, withoutSuffix?)到指定时间的相对时间

时间区间对照表:

范围Key输出示例
0 ~ 44 秒sa few seconds ago
45 ~ 89 秒ma minute ago
90 秒 ~ 44 分钟mm2 minutes ago ... 44 minutes ago
45 ~ 89 分钟han hour ago
90 分钟 ~ 21 小时hh2 hours ago ... 21 hours ago
22 ~ 35 小时da day ago
36 小时 ~ 25 天dd2 days ago ... 25 days ago
26 ~ 45 天Ma month ago
46 天 ~ 10 月MM2 months ago ... 10 months ago
11 月 ~ 17 月ya year ago
18 月+yy2 years ago ...

搭配中文 locale 使用效果更好:import 'dayjs/locale/zh-cn'dayjs.locale('zh-cn')


16. Calendar — 日历时间

路径: dayjs/plugin/calendar

作用: 返回"今天 下午2:30"、"昨天 上午10:00"这样的日历格式文字。

import calendar from 'dayjs/plugin/calendar'
dayjs.extend(calendar)

dayjs().calendar(dayjs('2008-01-01'))

// 自定义各场景的格式
dayjs().calendar(null, {
  sameDay: '[今天] HH:mm',           // 同一天
  nextDay: '[明天] HH:mm',           // 明天
  nextWeek: 'dddd HH:mm',           // 下周
  lastDay: '[昨天] HH:mm',           // 昨天
  lastWeek: '[上] dddd HH:mm',      // 上周
  sameElse: 'YYYY-MM-DD',           // 其他
})

五、周相关类

17. WeekOfYear — 年中第几周

路径: dayjs/plugin/weekOfYear

import weekOfYear from 'dayjs/plugin/weekOfYear'
dayjs.extend(weekOfYear)

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

18. WeekYear — 周年份

路径: dayjs/plugin/weekYear

依赖: 需先加载 WeekOfYear 插件

import weekOfYear from 'dayjs/plugin/weekOfYear'
import weekYear from 'dayjs/plugin/weekYear'
dayjs.extend(weekOfYear)
dayjs.extend(weekYear)

dayjs().weekYear()

19. IsoWeek — ISO 周

路径: dayjs/plugin/isoWeek

作用: 获取/设置 ISO 周数、ISO 星期几、ISO 周年份,并扩展 .startOf .endOf 支持 isoWeek 单位。

import isoWeek from 'dayjs/plugin/isoWeek'
dayjs.extend(isoWeek)

dayjs().isoWeek()       // ISO 周数
dayjs().isoWeekday()    // ISO 星期几(1=周一,7=周日)
dayjs().isoWeekYear()   // ISO 周年份

dayjs().startOf('isoWeek') // 本 ISO 周的起始(周一)
dayjs().endOf('isoWeek')   // 本 ISO 周的结束(周日)

20. IsoWeeksInYear — 一年有多少 ISO 周

路径: dayjs/plugin/isoWeeksInYear

依赖: 需先加载 IsLeapYear 插件

import isoWeeksInYear from 'dayjs/plugin/isoWeeksInYear'
import isLeapYear from 'dayjs/plugin/isLeapYear'
dayjs.extend(isoWeeksInYear)
dayjs.extend(isLeapYear)

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

21. Weekday — 本地化星期几

路径: dayjs/plugin/weekday

作用: 获取/设置基于 locale 的星期几(周日为第一天还是周一为第一天取决于 locale)。

import weekday from 'dayjs/plugin/weekday'
dayjs.extend(weekday)

// 当 locale 以周日为第一天时
dayjs().weekday(-7) // 上个周日
dayjs().weekday(7)  // 下个周日

// 当 locale 以周一为第一天时
dayjs().weekday(-7) // 上个周一
dayjs().weekday(7)  // 下个周一

六、UTC 与时区类

22. UTC — UTC 模式

路径: dayjs/plugin/utc

作用: 支持 UTC 模式下的解析和显示。

import utc from '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 → 本地时间
dayjs.utc().local().format()  // 2019-03-06T17:11:55+08:00

dayjs.utc().isUTC()  // true

API 说明:

方法说明
dayjs.utc(date?, format?)创建 UTC 模式的 Dayjs 对象
.utc()切换到 UTC 模式(返回新对象)
.local()切换到本地模式(返回新对象)
.utcOffset()获取/设置 UTC 偏移量
.isUTC()是否处于 UTC 模式

23. Timezone — 时区

路径: dayjs/plugin/timezone

依赖: 必须先加载 UTC 插件

作用: 跨时区解析和显示日期时间。

import utc from 'dayjs/plugin/utc'
import timezone from 'dayjs/plugin/timezone'
dayjs.extend(utc)
dayjs.extend(timezone)

// 在指定时区解析
const d1 = dayjs.tz('2013-11-18 11:55', 'Asia/Taipei')
d1.format()       // 2013-11-18T11:55:00+08:00
d1.toISOString()  // 2013-11-18T03:55:00.000Z

// 转换到指定时区
const d2 = dayjs.utc('2013-11-18 11:55').tz('Asia/Taipei')
d2.format()       // 2013-11-18T19:55:00+08:00

// 保留原始时间,仅改变时区标记
const d3 = dayjs('2014-06-01 12:00').tz('America/New_York', true)

// 猜测用户时区
dayjs.tz.guess()  // "Asia/Shanghai"

// 设置默认时区
dayjs.tz.setDefault('America/New_York')

// 重置为系统时区
dayjs.tz.setDefault()

API 说明:

方法说明
dayjs.tz(date, timezone)在指定时区解析
.tz(timezone, keepTime?)转换到指定时区
dayjs.tz.guess()猜测用户当前时区
dayjs.tz.setDefault(tz?)设置/重置默认时区

注意: dayjs(date) 始终使用本地时区,即使设置了 setDefault。只有 dayjs.tz(date)(不传第二个参数)才会使用默认时区。这和 moment.js 的行为不同。

七、持续时间类

24. Duration — 时间段

路径: dayjs/plugin/duration

作用: 创建和操作时间段对象(类似 moment.duration)。

import duration from 'dayjs/plugin/duration'
dayjs.extend(duration)

// 创建 duration
dayjs.duration(100)                           // 100 毫秒
dayjs.duration(2, 'days')                     // 2 天
dayjs.duration({ hours: 2, minutes: 30 })     // 2 小时 30 分
dayjs.duration('P1Y2M3DT4H5M6S')             // ISO 8601 格式

// 常用方法
const d = dayjs.duration(3661000)
d.years()        // 0
d.months()       // 0
d.days()         // 0
d.hours()        // 1
d.minutes()      // 1
d.seconds()      // 1
d.milliseconds() // 0

d.asHours()      // 1.0169...
d.asMinutes()    // 61.0166...
d.asSeconds()    // 3661

d.toISOString()  // "PT1H1M1S"
d.humanize()     // "an hour"(需 RelativeTime 插件)
d.humanize(true) // "in an hour"

// 运算
d.add(1, 'hours')
d.subtract(30, 'minutes')

// 判断是否是 duration
dayjs.isDuration(d) // true

八、数据转换类

25. ToArray — 转为数组

路径: dayjs/plugin/toArray

import toArray from 'dayjs/plugin/toArray'
dayjs.extend(toArray)

dayjs('2019-01-25').toArray()
// [2019, 0, 25, 0, 0, 0, 0]
// [年, 月(0起), 日, 时, 分, 秒, 毫秒]

26. ToObject — 转为对象

路径: dayjs/plugin/toObject

import toObject from '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 }

九、取值增强类

27. DayOfYear — 年中第几天

路径: dayjs/plugin/dayOfYear

import dayOfYear from 'dayjs/plugin/dayOfYear'
dayjs.extend(dayOfYear)

dayjs('2010-01-01').dayOfYear()     // 1
dayjs('2010-12-31').dayOfYear()     // 365
dayjs('2010-01-01').dayOfYear(365)  // 设置为第 365 天 → 2010-12-31

28. QuarterOfYear — 季度

路径: dayjs/plugin/quarterOfYear

作用: 获取/设置季度,并扩展 .add .subtract .startOf .endOf 支持 quarter 单位。

import quarterOfYear from 'dayjs/plugin/quarterOfYear'
dayjs.extend(quarterOfYear)

dayjs('2010-04-01').quarter()   // 2
dayjs('2010-04-01').quarter(2)  // 设置为第 2 季度

dayjs().add(1, 'quarter')
dayjs().subtract(1, 'quarter')
dayjs().startOf('quarter')
dayjs().endOf('quarter')

29. MinMax — 最大/最小日期

路径: dayjs/plugin/minMax

作用: 在多个 Dayjs 实例中取最大或最小值。

import minMax from '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'))

// 数组形式
dayjs.max([dayjs(), dayjs('2018-01-01'), dayjs('2019-01-01')])
dayjs.min([dayjs(), dayjs('2018-01-01'), dayjs('2019-01-01')])

30. PluralGetSet — 复数形式 getter/setter

路径: dayjs/plugin/pluralGetSet

作用: 增加所有时间单位的复数形式别名(兼容 moment.js 写法)。

import pluralGetSet from 'dayjs/plugin/pluralGetSet'
dayjs.extend(pluralGetSet)

// 以下两种写法等效
dayjs().millisecond()   // 单数(原生)
dayjs().milliseconds()  // 复数(插件新增)

// 支持的复数形式:
// .milliseconds() .seconds() .minutes() .hours()
// .days() .weeks() .isoWeeks() .months()
// .quarters() .years() .dates()

十、本地化与语言类

31. LocaleData — 语言数据

路径: dayjs/plugin/localeData

作用: 获取当前 locale 的详细信息(月名、星期名、首日设置等)。

import localeData from 'dayjs/plugin/localeData'
dayjs.extend(localeData)

// 全局快捷方法
dayjs.months()         // ['January', 'February', ...]
dayjs.monthsShort()    // ['Jan', 'Feb', ...]
dayjs.weekdays()       // ['Sunday', 'Monday', ...]
dayjs.weekdaysShort()  // ['Sun', 'Mon', ...]
dayjs.weekdaysMin()    // ['Su', 'Mo', ...]

// 全局 localeData 对象
const globalData = dayjs.localeData()
globalData.firstDayOfWeek()   // 0(周日)或 1(周一)
globalData.months()
globalData.monthsShort()
globalData.weekdays()
globalData.weekdaysShort()
globalData.weekdaysMin()
globalData.longDateFormat('L')  // 需同时加载 localizedFormat 插件
globalData.meridiem()
globalData.ordinal()

// 实例 localeData 对象
const instanceData = dayjs().localeData()
instanceData.firstDayOfWeek()
instanceData.months()
// ...(同上所有方法)

32. UpdateLocale — 更新语言配置

路径: dayjs/plugin/updateLocale

作用: 动态更新某个 locale 的属性。

import updateLocale from 'dayjs/plugin/updateLocale'
dayjs.extend(updateLocale)

dayjs.updateLocale('en', {
  months: [
    'January', 'February', 'March', 'April', 'May', 'June',
    'July', 'August', 'September', 'October', 'November', 'December'
  ],
  // 还可以更新 weekdays, relativeTime 等
})

33. PreParsePostFormat — 预解析 / 后格式化

路径: dayjs/plugin/preParsePostFormat

依赖: 需先加载 localeData 插件

作用: 在解析前和格式化后对字符串进行处理。主要用于非拉丁数字系统(如阿拉伯数字 ١٢٣ 与 123 的转换)。

import preParsePostFormat from 'dayjs/plugin/preParsePostFormat'
dayjs.extend(preParsePostFormat)

// 在 locale 配置中定义 preparse 和 postformat
const locale = {
  name: 'ar',
  // ...
  preparse(string) {
    // 将阿拉伯数字转为西方数字,然后再解析
    return string.replace(/[١٢٣٤٥٦٧٨٩٠]/g, match => numberMap[match])
  },
  postformat(string) {
    // 格式化输出后,将西方数字转为阿拉伯数字
    return string.replace(/\d/g, match => symbolMap[match])
  },
}

这是一个高级插件,一般开发者不太会用到。做国际化(非拉丁文数字)时才需要。

十一、特殊行为类

34. BadMutable — 可变模式(不推荐)

路径: dayjs/plugin/badMutable

作用: 让 Day.js 变成可变对象(mutable),所有 setter 操作会修改原对象。

import badMutable from 'dayjs/plugin/badMutable'
dayjs.extend(badMutable)

const today = dayjs()
today.add(1, 'day')
console.log(today) // 值已被修改为明天!

强烈不推荐使用! Day.js 设计为不可变对象。此插件仅用于从 moment.js 迁移过渡期的兼容。


35. DevHelper — 开发辅助

路径: dayjs/plugin/devHelper

作用: 在开发环境给出更多提示和警告信息。生产环境下可通过 process.env.NODE_ENV = 'production' 自动禁用。

import devHelper from 'dayjs/plugin/devHelper'
dayjs.extend(devHelper)

// 或按需加载
if (process.env.NODE_ENV !== 'production') {
  const devHelper = await import('dayjs/plugin/devHelper')
  dayjs.extend(devHelper.default)
}

建议在开发阶段启用,生产构建时 UglifyJS/Terser 会自动移除。

附录:插件速查总表

#插件名import 路径新增 API一句话说明
1AdvancedFormatadvancedFormat扩展 format()季度/序数日/Unix 时间戳格式
2LocalizedFormatlocalizedFormat扩展 format()L/LL/LLL 等本地化格式
3BuddhistErabuddhistEra扩展 format()佛历纪年格式 BBBB/BB
4CustomParseFormatcustomParseFormat扩展 dayjs()自定义格式字符串解析
5ArraySupportarraySupport扩展 dayjs()数组参数创建日期
6ObjectSupportobjectSupport扩展多个 API对象参数创建/操作日期
7BigIntSupportbigIntSupport扩展 dayjs()BigInt 参数支持
8IsBetweenisBetween.isBetween()判断日期是否在区间内
9IsSameOrAfterisSameOrAfter.isSameOrAfter()判断是否相同或之后
10IsSameOrBeforeisSameOrBefore.isSameOrBefore()判断是否相同或之前
11IsLeapYearisLeapYear.isLeapYear()判断是否闰年
12IsTodayisToday.isToday()判断是否今天
13IsTomorrowisTomorrow.isTomorrow()判断是否明天
14IsYesterdayisYesterday.isYesterday()判断是否昨天
15RelativeTimerelativeTime.from() .to() .fromNow() .toNow()相对时间(如"3小时前")
16Calendarcalendar.calendar()日历格式时间
17WeekOfYearweekOfYear.week()年中第几周
18WeekYearweekYear.weekYear()周年份
19IsoWeekisoWeek.isoWeek() .isoWeekday() .isoWeekYear()ISO 周相关
20IsoWeeksInYearisoWeeksInYear.isoWeeksInYear()该年有多少 ISO 周
21Weekdayweekday.weekday()本地化星期几
22UTCutc.utc() .local() .isUTC()UTC 模式解析/显示
23Timezonetimezone.tz() dayjs.tz() .tz.guess()跨时区处理
24Durationdurationdayjs.duration() dayjs.isDuration()时间段操作
25ToArraytoArray.toArray()转为数组
26ToObjecttoObject.toObject()转为对象
27DayOfYeardayOfYear.dayOfYear()年中第几天
28QuarterOfYearquarterOfYear.quarter()季度
29MinMaxminMaxdayjs.max() dayjs.min()取最大/最小日期
30PluralGetSetpluralGetSet.seconds() .hours()复数形式别名
31LocaleDatalocaleData.localeData() dayjs.months()获取语言数据
32UpdateLocaleupdateLocaledayjs.updateLocale()动态更新语言配置
33PreParsePostFormatpreParsePostFormatlocale 钩子预解析/后格式化
34BadMutablebadMutable改变默认行为可变模式(不推荐)
35DevHelperdevHelper开发提示开发环境辅助警告

附录:插件依赖关系图

独立插件(无依赖,直接用):
  AdvancedFormat, LocalizedFormat, BuddhistEra, CustomParseFormat,
  ArraySupport, ObjectSupport, BigIntSupport,
  IsBetween, IsSameOrAfter, IsSameOrBefore, IsLeapYear,
  IsToday, IsTomorrow, IsYesterday,
  RelativeTime, Calendar, WeekOfYear, IsoWeek,
  Weekday, DayOfYear, QuarterOfYear, MinMax,
  PluralGetSet, LocaleData, UpdateLocale,
  BadMutable, DevHelper, ToArray, ToObject, UTC, Duration

有依赖的插件:
  WeekYear         → 需先加载 WeekOfYear
  IsoWeeksInYear   → 需先加载 IsLeapYear
  Timezone         → 需先加载 UTC
  PreParsePostFormat → 需先加载 LocaleData

AdvancedFormat 的部分 token 需要额外插件:
  w/ww/wo → WeekOfYear
  W/WW    → IsoWeek
  gggg    → WeekYear
  GGGG    → IsoWeek
  z/zzz   → Timezone

附录:实战常用组合推荐

中文项目推荐加载

import dayjs from 'dayjs'
import 'dayjs/locale/zh-cn'
import relativeTime from 'dayjs/plugin/relativeTime'
import customParseFormat from 'dayjs/plugin/customParseFormat'
import advancedFormat from 'dayjs/plugin/advancedFormat'
import localizedFormat from 'dayjs/plugin/localizedFormat'
import isBetween from 'dayjs/plugin/isBetween'
import isSameOrBefore from 'dayjs/plugin/isSameOrBefore'
import isSameOrAfter from 'dayjs/plugin/isSameOrAfter'

dayjs.locale('zh-cn')
dayjs.extend(relativeTime)
dayjs.extend(customParseFormat)
dayjs.extend(advancedFormat)
dayjs.extend(localizedFormat)
dayjs.extend(isBetween)
dayjs.extend(isSameOrBefore)
dayjs.extend(isSameOrAfter)

需要时区处理时

import utc from 'dayjs/plugin/utc'
import timezone from 'dayjs/plugin/timezone'
dayjs.extend(utc)
dayjs.extend(timezone)

学习本就是一场持久战,不需要急着一口吃成胖子。哪怕今天你只记住了一点点,这都是实打实的进步。

后续我还会继续用这种大白话、讲实战方式,带大家扫盲更多前端基础。

关注我,不迷路,咱们把那些曾经模糊的知识点,一个个彻底搞清楚。

如果你觉得这篇内容对你有帮助,不妨点赞+收藏,下次写代码卡壳时,拿出来翻一翻,比搜引擎更靠谱。

我是 Eugene,你的电子学友,我们下一篇干货见~