js日期处理库--dayjs

js中处理日期是一件比较麻烦的事情,这里推荐使用day.js库来处理,文档:Day.js中文网

引入库

如果没有引入过dayjs,需要先执行npm install,然后import就能使用了

npm install dayjs
import dayjs from 'dayjs'

console.log(dayjs().format())

如果使用的是element plus,可以直接使用

import { dayjs } from 'element-plus'

console.log(dayjs().format())

解析

可以看到dayjs相当强大,各种格式的都能解析

let now = dayjs() //返回当前时间
console.log(now.format())
let date = dayjs('2018-04-04T20:00:00.000Z') // 解析ISO 8601格式的字符串
console.log(date.format())
date = dayjs("2024-08-09") //解析YYYY-MM-DD格式的
console.log(date.format())
date = dayjs("2024-08-09 10:04:05") //解析YYYY-MM-DD HH:mm:ss格式的
console.log(date.format())

显示 

使用format函数来格式化日期,支持的格式化字符见下表

let now = dayjs() //返回当前时间
now.format('YYYY-MM-DD')
now.format('YYYY-MM-DD HH:mm:ss')
now.format('YYYY年MM月DD日')
输入示例描述
YY18两位数的年份
YYYY2018四位数的年份
M1-12月份,从 1 开始
MM01-12月份,两位数
D1-31月份里的一天
DD01-31月份里的一天,两位数
H0-23小时
HH00-23小时,两位数
h1-12小时, 12 小时制
hh01-12小时, 12 小时制, 两位数
m0-59分钟
mm00-59分钟,两位数
s0-59
ss00-59秒,两位数

 相对当前时间(前)

这个功能在发布文章,发布消息时很有用,我们在看评论时可以看到发布在多少时间前,这个用day.js可以轻松实现

//day.js默认使用英文,需要加载中文包
import 'dayjs/locale/zh-cn'
dayjs.locale('zh-cn')
// 使用relativeTime插件
import relativeTime from 'dayjs/plugin/relativeTime'
//相对当前时间(前)
dayjs.extend(relativeTime)
dayjs('2024-07-10 11:30:00').fromNow()

 时间的比较

// 默认比较毫秒数,所以2024-08-10就是比较10号的零点零分
dayjs().isBefore('2024-08-10') //是否在这之前
//默认比较毫秒数,如果想比较天数就传day
dayjs().isSame('2024-08-09', 'day')
dayjs().isAfter('2024-08-07') // 是否在这之后

时间的差异

diff函数可以返回两个日期间相差多少

const date1 = dayjs()
//比较两个时间差异,返回月份,整数
date1.diff('2024-07-01', 'month')
//第三个参数传true就会返回浮点数
date1.diff('2024-07-01', 'month', true)

支持的单位如下

单位缩写描述
weekw周(Week of Year)
dayd
monthM月份 (一月 0, 十二月 11)
quarterQ季度,依赖 QuarterOfYear 插件
yeary
hourh小时
minutem分钟
seconds
millisecondms毫秒

操作 

获取或设置年份

dayjs().year() //获取年份
dayjs().year(2000) //设置年份

获取或设置月份

传入0到11的 number。 如果超出这个范围,它会进位到年份。

dayjs().month()
dayjs().month(0)

获取或设置月份里的日期

接受1到31的数字。 如果超出这个范围,它会进位到月份。

dayjs().date()
dayjs().date(1)

增加 

返回增加一定时间的复制的 Day.js 对象。

dayjs().add(7, 'day')

减去 

返回减去一定时间的复制的 Day.js 对象。

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

支持链式调用

dayjs('2019-01-25').add(1, 'day').subtract(1, 'year').year(2009).toString()

 时间的开始或结束

返回指定时间的开始或结束,这在某些日期查询里面很有用,比如查结束日期往往要传那天的23:59:59,就可以用endOf('day')来实现

dayjs('2024-08-09').startOf('year') //返回2024-01-01T00:00:00+08:00
dayjs('2024-08-09').startOf('month')//返回2024-08-01T00:00:00+08:00

dayjs('2024-08-09').endOf('year') //返回2024-12-31T23:59:59+08:00
dayjs('2024-08-09').endOf('month')//返回2024-08-31T23:59:59+08:00

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值