Day.js日期处理库使用

前言

Moment.js 的 2kB 轻量化方案,拥有同样强大的 API

Ant Design Vue 4中内置的日期处理就是这个库

https://day.js.org/zh-CN/

安装引用

1
npm install dayjs

引用

1
2
3
import dayjs from 'dayjs'
import 'dayjs/locale/zh-cn'
dayjs.locale('cn')

初始化

当前时间

1
var now = dayjs()

字符串

1
2
dayjs('2018-04-04T16:00:00.000Z')
dayjs('2018-04-13 19:18')

时间戳

毫秒

1
dayjs(1318781876406)

1
dayjs.unix(1318781876)

Date对象

1
2
var d = new Date(2018, 8, 18)
var day = dayjs(d)

复制

所有的 Day.js 对象都是 不可变的。 但如果有必要,使用 dayjs#clone 可以复制出一个当前对象

1
2
var a = dayjs()
var b = a.clone()

转其它类型

转字符串

1
2
dayjs().format("YYYY-MM-DD"); 
dayjs().format("YYYY-MM-DD HH:mm:ss");

时间戳

1
2
3
4
//毫秒
dayjs().valueOf()
//秒
dayjs().unix()

取值和赋值

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
dayjs().second() // gets current second
dayjs().second(1) // returns new dayjs object

dayjs().minute() // gets current minute
dayjs().minute(59) // returns new dayjs object

//传入0到23的数字。 如果超出这个范围,它会进位到天数。
dayjs().hour() // gets current hour
newDate = dayjs().hour(12) // returns new dayjs object

dayjs().date() // gets day of current month
dayjs().date(1) // returns new dayjs object

//月份是从 0 开始计算的,即 1 月是 0。
dayjs().month() // gets current month
dayjs().month(0) // returns new dayjs object

dayjs().year() // gets current year
dayjs().year(2000) // returns new dayjs object

日期处理

1
2
3
dayjs().add(7, 'day')

dayjs().subtract(7, 'year')

支持的单位列表

单位 缩写 详情
day d
week w
month M
quarter Q 季度 ( 依赖 QuarterOfYear 插件 )
year y
hour h 小时
minute m 分钟
second s
millisecond ms 毫秒

日期计算

1
2
3
4
5
6
7
8
9
10
const dayjs = require('dayjs');

// 定义两个日期
const date1 = dayjs('2024-10-11');
const date2 = dayjs('2024-11-10');

// 计算两个日期之间的天数差异
const diffInDays = date2.diff(date1, 'day');

console.log(`两个日期相差 ${diffInDays} 天`);

日期比较

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
const dayjs = require('dayjs');

// 指定日期,可以根据需求修改格式
const specifiedDate = dayjs('2025-03-01');

// 获取当前日期
const currentDate = dayjs();

// 判断当前日期是否在指定日期之后
const isAfter = currentDate.isAfter(specifiedDate);

if (isAfter) {
console.log('当前日期在指定日期之后');
} else {
console.log('当前日期不在指定日期之后');
}

TS

1
2
3
4
5
6
7
8
9
10
export function isAfterDateStr(datetime: string) {
// 指定日期,可以根据需求修改格式
const specifiedDate = dayjs(datetime)

// 获取当前日期
const currentDate = dayjs()

// 判断当前日期是否在指定日期之后
return currentDate.isAfter(specifiedDate)
}

TS中使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import type { Dayjs } from 'dayjs'

const beginDateObj = ref<Dayjs>()
const endDateObj = ref<Dayjs>()
watch(beginDateObj, () => {
if (beginDateObj.value) {
filterObj.begindate = beginDateObj.value.format('YYYY-MM-DD')
} else {
filterObj.begindate = ''
}
})

watch(endDateObj, () => {
if (endDateObj.value) {
filterObj.enddate = endDateObj.value.format('YYYY-MM-DD')
} else {
filterObj.enddate = ''
}
})