前言
Moment.js 的 2kB 轻量化方案,拥有同样强大的 API
Ant Design Vue 4中内置的日期处理就是这个库
https://day.js.org/zh-CN/
安装引用
引用
1 2 3
| import dayjs from 'dayjs' import 'dayjs/locale/zh-cn' dayjs.locale('cn')
|
初始化
当前时间
字符串
1 2
| dayjs('2018-04-04T16:00:00.000Z') dayjs('2018-04-13 19:18')
|
时间戳
毫秒
秒
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() dayjs().second(1)
dayjs().minute() dayjs().minute(59)
dayjs().hour() newDate = dayjs().hour(12)
dayjs().date() dayjs().date(1)
dayjs().month() dayjs().month(0)
dayjs().year() dayjs().year(2000)
|
日期处理
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 = '' } })
|