• 微信:WANCOME
  • 扫码加微信,提供专业咨询
  • 服务热线
  • 13215191218
    13027920428

  • 微信扫码访问本页
desc-2
环企首页

dayjs

概述

dayjs 是 Moment.js 的轻量级替代品,API 与 Moment.js 完全兼容,体积仅约 2KB。几乎实现了 Moment.js 的所有功能,同时支持插件扩展。所有 API 均返回新的 dayjs 实例(不可变),链式调用友好。

核心特点:

  • 2KB 极小体积
  • 完全兼容 Moment.js API(学习成本为零)
  • 不可变设计
  • 插件化架构

安装:

npm install dayjs

核心函数

dayjs(input)

创建 dayjs 实例。

const dayjs = require('dayjs')

dayjs()                        // 当前时间
dayjs('2024-01-01')           // 从字符串解析
dayjs(new Date())             // 从 Date 对象
dayjs(1704067200000)          // 从时间戳(毫秒)
dayjs.unix(1704067200)        // 从 Unix 时间戳(秒)
dayjs().format('YYYY-MM-DD')  // '2024-01-01'

解析与创建

dayjs('2024-01-01')                    // 字符串
dayjs('2024/01/01')                    // 支持 /
dayjs('2024-01-01T12:00:00+08:00')    // ISO 8601
dayjs('01/01/2024', 'MM/DD/YYYY')      // 指定格式
dayjs().startOf('day')                 // 今天 00:00:00
dayjs().endOf('day')                   // 今天 23:59:59
dayjs().startOf('month')               // 本月第一天
dayjs().endOf('month')                 // 本月最后一天

格式化

dayjs().format('YYYY-MM-DD')           // '2024-01-01'
dayjs().format('YYYY年MM月DD日')       // '2024年01月01日'
dayjs().format('HH:mm:ss')             // '12:30:45'
dayjs().format('YYYY-MM-DD HH:mm')     // '2024-01-01 12:30'
dayjs().format('dddd')                  // '星期一'(中文需加载 locale)
dayjs().format('MMMM Do, YYYY')         // '一月 1日, 2024'

// 格式化占位符:
// YYYY(4位年)YY(2位年)M(无补0月)MM(补0月)
// D(无补0日)DD(补0日)
// H(24h无补0)HH(24h补0)h(12h无补0)hh(12h补0)
// m(无补0分)mm(补0分)s(无补0秒)ss(补0秒)
// d(0-6)ddd(缩写)dddd(完整)
// A(AM/PM)a(am/pm)

时间计算

dayjs().add(1, 'day')                  // 加 1 天
dayjs().add(1, 'week')                 // 加 1 周
dayjs().add(1, 'month')                // 加 1 月
dayjs().add(1, 'year')                 // 加 1 年
dayjs().add(2, 'hour')                // 加 2 小时
dayjs().add(30, 'minute')             // 加 30 分钟
dayjs().add(-1, 'day')                // 减 1 天(等价于 subtract)

dayjs().subtract(1, 'day')            // 减 1 天

// 支持链式
dayjs().add(1, 'day').add(2, 'hour').subtract(30, 'minute')

时间差

dayjs('2024-01-01').diff(dayjs('2024-01-02'))        // -86400000(ms)
dayjs('2024-01-01').diff(dayjs('2024-01-02'), 'day') // -1(天)
dayjs('2024-01-01').diff(dayjs('2024-01-03'), 'week') // 0(向上取整)

// 精确到小数
dayjs('2024-01-01').diff(dayjs('2024-01-01 12:00:00'), 'hour', true) // -12.0

// 常用场景:计算年龄
const age = dayjs().diff(dayjs('1990-01-01'), 'year')

// 计算工期
const days = dayjs(endDate).diff(dayjs(startDate), 'day') + 1

查询

dayjs().isBefore(dayjs())              // 是否在另一个时间之前
dayjs().isAfter(dayjs())               // 是否在另一个时间之后
dayjs().isSame(dayjs())                // 是否相同
dayjs().isSame(dayjs(), 'year')        // 是否同一年
dayjs().isSame(dayjs(), 'month')       // 是否同一月
dayjs().isSame(dayjs(), 'day')         // 是否同一日

dayjs().isBetween(start, end)          // 是否在范围内
dayjs().isBetween(start, end, 'day')   // 按天比较
dayjs().isBetween(start, end, null, '()') // 开区间 '()' 或 '[]' 闭区间

时间戳

dayjs().valueOf()                      // 毫秒时间戳
dayjs().unix()                        // 秒时间戳
dayjs().toDate()                       // 转为 Date 对象
dayjs().toISOString()                  // ISO 8601 字符串
dayjs().toJSON()                       // 等同 toISOString
dayjs().toString()                     // 原始字符串

常用工具

dayjs().startOf('year')               // 年初
dayjs().endOf('year')                 // 年末
dayjs().startOf('month')              // 月初
dayjs().endOf('month')                // 月末
dayjs().startOf('week')              // 周初(默认周日)
dayjs().endOf('week')                // 周末
dayjs().week()                        // 一年中的第几周(需 weekOfYear 插件)
dayjs().quarter()                     // 季度(需 quarterOfYear 插件)

dayjs().daysInMonth()                 // 当月天数(28-31)
dayjs().year()                        // 年
dayjs().month()                       // 月(0-11)
dayjs().date()                        // 日(1-31)
dayjs().day()                         // 周几(0-6,0=周日)
dayjs().hour()                        // 小时(0-23)
dayjs().minute()                      // 分钟
dayjs().second()                      // 秒
dayjs().millisecond()                 // 毫秒

常用插件

UTC

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

dayjs().utc().format('YYYY-MM-DD HH:mm:ss')  // 转为 UTC 时间
dayjs().utcOffset(8).format()                 // 固定偏移 +8 小时

RelativeTime(相对时间)

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

dayjs().to(dayjs().subtract(1, 'hour'))  // '2小时前'
dayjs().toNow()                          // '5分钟前'
dayjs().from(dayjs().add(1, 'hour'))     // '1小时前'
dayjs().fromNow()                        // '5分钟内'

Duration(时长)

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

dayjs.duration(60000).as('seconds')      // 60
dayjs.duration(2, 'hours').as('minutes') // 120
dayjs.duration({ days: 5, hours: 12 }).format('D天H小时') // '5天12小时'

其他常用插件

const localizedFormat = require('dayjs/plugin/localizedFormat')
const isSameOrBefore = require('dayjs/plugin/isSameOrBefore')
const isSameOrAfter = require('dayjs/plugin/isSameOrAfter')
const isBetween = require('dayjs/plugin/isBetween')
const weekOfYear = require('dayjs/plugin/weekOfYear')
const quarterOfYear = require('dayjs/plugin/quarterOfYear')
const calendar = require('dayjs/plugin/calendar')
const advancedFormat = require('dayjs/plugin/advancedFormat')

dayjs.extend(localizedFormat)   // format('L') → '2024/01/01'
dayjs.extend(isSameOrBefore)
dayjs.extend(isSameOrAfter)
dayjs.extend(isBetween)
dayjs.extend(weekOfYear)
dayjs.extend(quarterOfYear)
dayjs.extend(calendar)
dayjs.extend(advancedFormat)    // format('Q') → '1st quarter'

常见问题

问题 解决方案
格式化返回中文星期 加载 locale('zh-cn')
时间比较报错 确保两边都是 dayjs 对象再比较
UTC 时间处理错误 加载 utc 插件
add(1, 'month') 跨月越界 dayjs('2024-01-31').add(1, 'month') → 2024-02-29(自动处理)
Moment.js 迁移 直接替换 require('moment')require('dayjs'),API 兼容