工作中经常使用dayjs用来处理时间问题,记录一下最近使用的dayjs
1.使用dayjs获取某个时间的时间戳
dayjs('2022-07-29 10:12:01').toDate().getTime()
2.format日期格式
dayjs('2022-07-29 10:12:01').format('YYYY-MM-DD') //2022-07-29
dayjs('2022-07-29 10:12:01').format('YYYY-MM') //2022-07
dayjs('2022-07-29 10:12:01').format('HH:mm:ss') //10:12:01
具体可以查看这里->dayjs格式化
3.加减等操作日期
如:指定日期减去一个月
dayjs('2022-07-29').subtract(1, 'month').format('YYYY-MM-DD') //2022-06-29
更多操作方法看这里->dayjs日期操作
4.结合dayjs将某个时间段格式化成时分秒显示
如果想把某个时间段格式化成时分秒的样子,可以用下面方法:
millisecondFormat('2022-07-27 08:00:01', '2022-07-27 13:55:01') //5小时55分
millisecondFormat('2022-07-27 08:00:00', '2022-07-27 20:00:01') //12小时
millisecondFormat('2022-07-27 08:00:00','2022-07-27 08:30:00') //30分
具体实现
/**
* 将毫秒数调整为显示时分秒,如小于等于60分钟则显示XX分,如大于60分钟则显示XX小时XX分
* @param {*} millisecond 待转换的毫秒数
*/
millisecondFormat(startDate, endDate) {
let startTime = dayjs(startDate, 'YYYY-MM-DD HH:mm:ss').toDate().getTime()
let endTime = dayjs(endDate, 'YYYY-MM-DD HH:mm:ss').toDate().getTime()
let surplus = endTime - startTime
const hour = Math.floor(NP.divide(surplus, 60 * 60 * 1000))
surplus = surplus % (60 * 60 * 1000)
const minute = Math.floor(NP.divide(surplus, 60 * 1000))
surplus = surplus % (60 * 1000)
// const second = Math.floor(NP.divide(surplus, 1000))
// return hour > 0 ? `${this.addZero(hour)}小时${this.addZero(minute)}分` : `${this.addZero(minute)}分${this.addZero(second)}秒`
return hour > 0 ? `${hour}小时${this.addZero(minute)=='00'?'':this.addZero(minute)+'分'}` : `${this.addZero(minute)}分`
},
/**
* 不足两位补零
* @param {Number} val
*/
addZero(val) {
return val > 9 ? val : `0${val}`
}
5.将时间段换算成长度
假设一小时长度为100px,将某段开始时间-结束时间换算成长度如下:
timeRangeToWidth2('2022-07-27 15:35:16','2022-07-27 23:13:53') //313.22222222222223px
具体实现
/**
* 将毫秒数转换为显示宽度
* @param {*} startDate 开始时间
* @param {*} startDate 结束时间
*/
timeRangeToWidth2(startDate, endDate) {
let startTime = dayjs(startDate, 'YYYY-MM-DD HH:mm:ss').toDate().getTime()
let endTime = dayjs(endDate, 'YYYY-MM-DD HH:mm:ss').toDate().getTime()
let timeRange = endTime - startTime
const range = NP.divide(timeRange, 60 * 60 * 1000)
let rlt = `${NP.times(range, 100)}px`
return rlt
},
方法中使用了另一个npm工具类 number-precision,具体使用
到底啦~
在项目开发过程中,处理日期的地方还是蛮多的,先记录一下最近使用过的,后面有遇到其它的再继续....By the way 今天周五啦哈哈,周五万岁 -3-