day.js diff 方法详解

day.js diff 方法详解

day.jsdiff 方法返回指定单位下两个日期时间之间的差异,默认以毫秒为单位,返回值可以为负数。

示例一、基础使用

默认返回毫秒差异

const date1 = dayjs('2022-11-14') const date2 = dayjs('2022-01-25') date1.diff(date2) // 25315200000 date2.diff(date1) // -25315200000

示例二、指定差异单位

要获取其他单位下的差异,则在第二个参数传入相应的单位。

const date1 = dayjs('2022-11-14') const date2 = dayjs('2022-01-25') date1.diff(date2, 'month') // 9

示例三、获得更高精度的差异

默认情况下 dayjs#diff 会将结果进位成整数。 如果要得到一个浮点数,将 true 作为第三个参数传入。

const date1 = dayjs('2022-11-14') const date2 = dayjs('2022-01-25') date1.diff(date2, 'week',true) //41.857142857142854

支持的单位列表

传入的单位对大小写不敏感,同时支持缩写和复数。 但是缩写是区分大小写的。


单位缩写详情
dayd星期几 (星期天0,星期六6)
weekw
quarterQ季度
monthM月份 (一月 0, 十二月 11)
yeary
hourh
minutem
seconds
millisecondms毫秒




文章评论 (0)

暂无评论,快来抢沙发吧!

发表评论