两段代码对比
1. 时间操作
1setTimeout(() => {2 // xxx代码逻辑3}, 60 * 60 * 1000)
2. 用Dayjs操作
1const oneHour = dayjs.duration(1, 'hours').asMilliseconds()2
3setTimeout(() => {4 // xxx代码逻辑5}, oneHour)
哪段代码更容易理解?
显然,第二段代码更加的语义化,一眼就能看懂定时器的时长。
dayjs介绍
dayjs是一个core只有2kb的包,用于替代庞大的momentjs。它提供了相似的API,便于从momentjs迁移代码。
dayjs也设计了插件体系,一些不太常用的大体积功能可以用插件的方式引入。
dayjs的方法名直观表达意图,参数结构符合自然思维,并支持链式调用,可以减少出错的可能,推荐使用它替换代码中的手写时间日期操作代码。
常用场景介绍
从字符串parse时间
字符串需要满足ISO 8601标准。
1dayjs('2018-04-04T16:00:00.000Z')2dayjs('2018-04-13 19:18:17.040+02:00')3dayjs('2018-04-13 19:18')
JS Date & dayjs格式互转
1var d = new Date(2018, 8, 18)2var day = dayjs(d)3
4var date = day.toDate()
时间的读 & 写
1dayjs().valueOf() // 获取当前时间戳2
3dayjs().second(30) // 设置秒为304dayjs().second() // 读取秒
时间格式化
1dayjs().format('YYYY-MM-DD HH:mm:ss')
时间差异
1const date1 = dayjs('2019-01-25')2const date2 = dayjs('2018-06-05')3date1.diff(date2) // 返回毫秒数 202176000004
5
6// 计算在具体的单位上时间差异7const date1 = dayjs('2019-01-25')8// 去除小数部分9date1.diff('2018-06-05', 'month') // 710// => 精确小数11date1.diff('2018-06-05', 'month', true) // 7.645161290322581
时间前后比较
isAfter
1// 默认从毫秒开始比较2dayjs().isAfter(dayjs('2024-11-03')) // true3// 例如从月开始比(月 + 年) => 第二个参数传入比较的最低单位4dayjs().isAfter(dayjs('2024-11-03'), 'month') // false
isBefore
、isSame
API用法相同。
isSameOrAfter
、isSameOrBefore
=> 包含比较的边界,需要额外引入IsSameOrBefore
插件使用。
isBetween
: 判断是否在两个时间的中间,需要额外引入 IsBetween
插件使用。也支持传入比较的最低单位。
1dayjs.extend(isBetween)2dayjs('2010-10-20').isBetween('2010-10-19', dayjs('2010-10-25')) // true3
4dayjs('2010-10-20').isBetween('2010-10-19', '2010-10-25', 'month') // false
时间加减
例如从一个固定时间获取一个小时后的时间,可以用add
、subtract
实现。
1var a = dayjs('2024-11-03')2a.add(2, 'day') // => 对象变为2024-11-05的值3a.substract(1, 'day') // => 对象变为2024-11-04的值
时长对象
1dayjs.extend(duration)2
3dayjs.duration({ months: 12 })4dayjs.duration(12, 'm'); // 和上面对象形式等价
支持时长的加减
1var a = dayjs.duration(1, 'd');2var b = dayjs.duration(2, 'd');3
4a.add(b).days(); // 35a.add({ days: 2 } ).days();6a.substract(2, 'days');
时间对象支持加减时长
1var a = dayjs('2024-11-03')2var b = dayjs.duration(2, 'd')3
4a.add(b).date(); // 5