Day.js 使用记录

Web

Day.js 是一个极简的JavaScript库,可以为现代浏览器解析、验证、操作和显示日期和时间。

安装

1
npm install dayjs

引入

1
import * as dayjs from 'dayjs'

基本用法

当前时间

1
dayjs() // === dayjs(new Daye())

格式化

根据传入的占位符返回格式化后的日期。

1
dayjs('2022/2/16').format('YYYY-MM-DD') // '2022-2-16' 

差异

返回指定单位下两个日期时间之间的差异,默认返回毫秒为单位的差异。

第二个参数指定单位,第三个参数为 true 时返回浮点数。

1
2
const date1 = dayjs('2019-01-25')
date1.diff('2018-06-05', 'month', true) // 7.645161290322581

可以用来计算日期到日期一共多少天:

1
2
3
const calculateTime = (date1, date2) => {
return dayjs(date2).diff(dayjs(date1), 'day') + 1
}

时间的开始以及结束

返回复制的 Day.js 对象,并设置到一个时间的开始或者结束。

1
2
dayjs().startOf('day').format('YYYY/MM/DD HH:mm:ss') // 2023/02/22 00:00:00
dayjs().endOf('month').format('YYYY/MM/DD HH:mm:ss') // 2023/02/28 23:59:59

实践

返回 N 个月前的时间段或当月的时间段:

1
2
3
4
5
const getMonthArray = (n: number = 0) => {
const start = dayjs().subtract(n, 'month').startOf('month').valueOf()
const end = n === 0 ? dayjs().valueOf() : dayjs().subtract(n, 'month').endOf('month').valueOf()
return [start, end]
}

本文作者:Kiro

本文链接: https://www.kiro.cc/2023/02/day-js/