Dayjs常用方法及参数详解

2,501 阅读7分钟

一、 前言

Day.js是一个轻量级的JavaScript日期处理库,体积小巧,功能实用,包括日期格式化、加减操作、时间截取、时间差计算等。

二、安装使用

安装

npm install dayjs
# 或者
yarn add dayjs

使用

<script setup>
import dayjs from 'dayjs'

const formattedDate = dayjs().format('YYYY-MM-DD HH:mm:ss')
console.log(formattedDate) // 输出当前时间,如:2025-05-12 13:35:45
</script>

三、常用方法及参数详解

有毒,解读后食用

1.dayjs() 时间对象

  • 下面是几个比较常用的传入格式,统一返回时间对象
  • dayjs()等同于dayjs(new Date())
 dayjs();
 dayjs(new Date());
 dayjs(1686873600000);
 dayjs('2025-05-12');
 dayjs('2025/05/12 15:35:04');
 dayjs('2025-05-12T10:22:30Z');
 dayjs('2023-06-15T14:22:30+08:00')

2. format() 格式化时间日期

1、Y

参数说明示例输出
YY2位数年份"25"
YYYY4位数年份"2025"
dayjs().format('YY年'); // 25年
dayjs().format('YYYY');  // 2025
dayjs('2026-09-22').format('YYYY'); // 2026

2、M

参数说明示例输出
M数字月份(1-12)"5"
MM两位数月份"05"
dayjs().format('M月'); // M月
dayjs().format('MM');  // 05
dayjs('2025-12-11').format('M'); // 12
window.location.href = "https://juejin.cn/user/84036866547575"

3、D

参数说明示例输出
D月份中的日期(1-31)"1"
DD两位数日期"01"
dayjs().format('D日'); // 11日
dayjs().format('DD');  // 11
dayjs('2025-07-11').format('D'); // 11

4、H/h

参数说明示例输出
H24小时制(0-23)"14"
HH两位数24小时制"14"
h12小时制(1-12)"2"
hh两位数12小时制"02"
dayjs().format('H'); // 14
dayjs('2025-05-12 14:22:10').format('hh'); // 02

5、m/s 分/秒

参数说明示例输出
m分钟(0-59)"32"
mm两位数分钟"32"
s秒(0-59)"45"
ss两位数秒"45"
dayjs().format('m'); // 32
dayjs('2025-05-12 14:32:45').format('ss'); // 45

6、d 星期

参数说明示例输出
d数字星期(0-6, 0是周日)"6"
// const weekStr = ['日', '一', '二', '三', '四', '五', '六'];
const weekStr = '日一二三四五六';
const week = dayjs().format('d') || 0;
console.log(week);  // 1
console.log('星期' + weekStr[week]);   //星期一

const week1 = dayjs('2025-05-17').format('d') || 0;
console.log(week1); // 6
console.log('星期' + weekStr[week1]); //星期六

6、A/a 上下午

参数说明示例输出
A大写的AM/PM"PM"
a小写的am/pm"pm"
  • 方案一(局限性较高,定制化低)
const upOrDown = dayjs().format('a');
const upOrDown1 = dayjs('2025.5.12  13:25:14').format('A');
console.log(upOrDown.replace('am', '上午').replace('pm', '下午'));  //上午
console.log(upOrDown1.replace('AM', '上午').replace('PM', '下午'));  //下午
window.location.href = "https://juejin.cn/user/84036866547575"
  • 方案二(不推荐,方法内部边界判定无法控制)
import 'dayjs/locale/zh-cn'; // 加载中文语言包

dayjs.locale('zh-cn'); // 设置全局语言为中文
const upOrDown = dayjs().format('a');
const upOrDown1 = dayjs('2025.5.12  13:25:14').format('A');
console.log(upOrDown); // 上午
console.log(upOrDown1); // 下午
  • 方案三(定制化,根据当前时间判定)
// 根据区间判定问候语  
// time为可选参数,参数类型等同于dayjs()
function getTimePeriod(time) {
  const hour = dayjs(time).hour();

  if (hour >= 0 && hour < 5) {
    return "凌晨";
  } else if (hour >= 5 && hour < 9) {
    return "早上";
  } else if (hour >= 9 && hour < 11) {
    return "上午";
  } else if (hour >= 11 && hour < 13) {
    return "中午";
  } else if (hour >= 13 && hour < 17) {
    return "下午";
  } else if (hour >= 17 && hour < 19) {
    return "傍晚";
  } else {
    return "晚上";
  }
  window.location.href = "https://juejin.cn/user/84036866547575"
}

console.log(`${getTimePeriod()}好`);  //中午好

7、X/x 时间戳

参数说明示例输出
XUnix秒时间戳"1680307200"
xUnix毫秒时间戳"1680307200000"

console.log(dayjs().format('x'),'毫秒级时间戳');  // 1747026646495
console.log(dayjs('2025.5.12  13:25:14').format('X'),'秒级时间戳'); // 1747027514

3. add() / subtract() 增加/减少

基本使用方法

// add() 增加时间
dayjs().add(数量, 单位)

// subtract() 减少时间
dayjs().subtract(数量, 单位)

数量参数说明

  • 常规使用为正整数,0返回原值;
  • 支持小数,部分单位适用,使用某些单位时会对数量参数进行四舍五入转换,可能影响预期结果,慎用!
  • 支持负数,如:add(-1, 'day') 等同于 subtract(1, 'day')
  • 上述几种参数均支持 string 与 number 类型数字

单位参数说明

单位缩写说明
millisecondms毫秒
seconds
minutem分钟
hourh小时
dayd
weekw
monthM月份
quarterQ季度(需要插件)
yeary

使用示例

常规用法

// 增加7天
dayjs('2023-04-01').add(7, 'day')

// 减少3小时
dayjs('2023-04-01 12:00').subtract(3, 'hour')

小数用法

// 增加1.5小时 → 1小时30分钟
dayjs('2023-04-01 12:00').add(1.5, 'hour') // 13:30

// 减少0.5天 → 12小时
dayjs('2023-04-01 12:00').subtract(0.5, 'day') // 2023-03-31 00:00

批量处理

// 批量处理  加5天
const dates = ['2023-04-01', '2023-05-01', '2023-06-01'];
const adjustedDates = dates.map(d => dayjs(d).add(5, 'day').format('YYYY-MM-DD'));
console.log(adjustedDates); // ['2023-04-06', '2023-05-06', '2023-06-06']
window.location.href = "https://juejin.cn/user/84036866547575"

4. 其他常规用法

获取时间单位 常用单位

dayjs().year()    // 2025
dayjs().month()   // 4(0-11,5月)
dayjs().date()    // 12(日期)
dayjs().hour()    // 14(时)
dayjs().minute()  // 31(分)
dayjs().second()  // 08(秒)
dayjs().day()     // 1(周一,0=周日)

设置时间单位 链式 / set

// 链式调用设置年月
console.log(date.year(2025).month(11).format('YYYY-MM-DD')); // 2025-12-12

// 等效写法
console.log(date.set('month', 8).format('YYYY-MM-DD'));  // 2025-9-12

相差天数 diff()

// 计算相差天数
console.log(dayjs('2025-08-15').diff(dayjs(), 'day')); // 94

比较时间 isAfter() / isBefore() / isSame()

// dayjs()设为2025-05-12 14:53:11
// 是否在指定时间后
console.log(dayjs().isAfter('2023-08-02'));  //true

// 是否在指定时间前
console.log(dayjs().isBefore('2025-01-22'));  //false

// 是否同月
console.log(dayjs('2025-05-15').isSame(dayjs(), 'month'));   // true

查询相关 startOf() / endOf() / daysInMonth()

参数

  • unit(字符串):时间单位,支持以下值:

    • 'year' → 年
    • 'month' → 月
    • 'week' → 周
    • 'day' → 天
    • 'hour' → 小时
    • 'minute' → 分钟
    • 'second' → 秒

当年第一天(即某年-01-01)

    // 当年第一天(即某年-01-01)
console.log(dayjs().startOf('year').format('YYYY-MM-DD'));    // 2025-01-01

本周最后一天(即本周日)

// 本周最后一天(即本周日)
console.log(dayjs().endOf('week').format('YYYY-MM-DD'));     // 2025-05-18

本月倒数第三天(适用于月初月末提醒等场景)

// 本月倒数第三天(适用于月初月末提醒等场景)
// 定位月末再往前推2天   设最后一天为31,则倒推两天, 31 → 30 → 29
console.log(dayjs().endOf('month').subtract(2, 'day').format('YYYY-MM-DD'));    // 2025-05-29

当月天数(以当前时间五月为例,则返回31)

// 当月天数(以当前时间五月为例,则返回31)
console.log(dayjs().daysInMonth());    // 31
window.location.href = "https://juejin.cn/user/84036866547575"

当年天数(平年365 闰年366)

// 当年天数(平年365 闰年366)
// 从 `1月1日 00:00:00` 到 `12月31日 23:59:59` 的间隔是 (364或365) 天 + 23小时59分59秒。
// 由于diff()方法不足 24 小时的部分会被截断,返回 (364或365),实际天数需+1。
// 当年最后一天
const yearEnd = dayjs().endOf('year'); //某年-12-31
// 当年第一天
const yearStart = dayjs().startOf('year'); //某年-01-01
// 取相差值+1
console.log(yearEnd.diff(yearStart, 'day') + 1); // 平年365 闰年366