Skip to content

Day.js

介绍

Day.js 体积仅 2KB,API 高度兼容 Moment.js

创建时间

js
dayjs() // 当前时间
dayjs('2025-06-15') // 指定日期
dayjs('2025-06-15 14:30', 'YYYY-MM-DD HH:mm') // 需要插件:customParseFormat
dayjs.unix(1718448000) // Unix 时间戳(秒)
dayjs(new Date()) // 原生 Date 转换

格式化时间

js
dayjs().format() // 默认:2025-06-15T12:34:56+08:00
dayjs().format('YYYY-MM-DD') // 2025-06-15
dayjs().format('YYYY年M月D日 HH:mm') // 2025年6月15日 14:30

获取时间信息

js
dayjs().year() // 年
dayjs().month() // 月(0-11)
dayjs().date() // 日
dayjs().hour() // 时
dayjs().minute() // 分
dayjs().second() // 秒
dayjs().day() // 星期几(0是星期日)

时间运算

js
dayjs().add(3, 'day') // 加3天
dayjs().subtract(1, 'month') // 减1个月
dayjs().startOf('month') // 月初
dayjs().endOf('week') // 周末

支持单位:year, month, week, day, hour, minute, second, millisecond

时间比较

js
dayjs('2025-06-15').isBefore('2025-07-01') // true
dayjs().isAfter('2024-01-01') // true
dayjs().isSame('2025-06-15', 'day') // 是否同一天

时间差

需要插件:durationrelativeTime

bash
npm install dayjs/plugin/duration dayjs/plugin/relativeTime
js
import duration from 'dayjs/plugin/duration'
import relativeTime from 'dayjs/plugin/relativeTime'
dayjs.extend(duration)
dayjs.extend(relativeTime)

const a = dayjs('2025-06-15')
const b = dayjs('2025-07-01')

b.diff(a, 'day') // 16
dayjs.duration(b.diff(a)).humanize() // “16 天”
dayjs().from(dayjs('2025-06-01')) // “14 天前”

本地化(中文)

js
import 'dayjs/locale/zh-cn'
dayjs.locale('zh-cn')

dayjs().format('dddd') // 星期日
dayjs().fromNow() // 几秒前
dayjs().calendar() // 需插件(不内置)

其他 API

js
dayjs().toDate() // 转原生 Date
dayjs().toISOString() // 转 ISO 字符串
dayjs().unix() // 秒时间戳
dayjs().valueOf() // 毫秒时间戳

推荐插件一览

插件名功能简述
utc支持 UTC 时间
timezone支持时区转换
localeData支持获取星期几、月份名称等
customParseFormat自定义字符串解析
duration时间段差值(与 diff 配合)
relativeTime相对时间(几分钟前)
advancedFormat支持 Moment 的更多格式符号
calendar显示“今天”、“昨天”样式

使用插件:

js
import plugin from 'dayjs/plugin/xxx'
dayjs.extend(plugin)

基于 MIT 许可发布