在日常开发中,经常会遇见对日期进行格式化,比如将日期格式化为"刚刚"、"几分钟前"、"昨天"、"几天前"、"YYYY-MM-DD hh:mm:ss"等等,为此基于day.js封装了一个小函数,代码如下
//utils.js
import dayjs from 'dayjs'
//对传入的日期格式无限制可以是YYYY-MM-DD hh:mm:ss也可以是时间戳
const formatDate = (t=Date.now()) => {
if(!t) return ''
// 获取当前日期
const now = dayjs();
// 模拟一个过去的日期
const pastDate = dayjs(t);
// 计算时间差/分
const diff = now.diff(pastDate, 'minute');
// 计算时间差/时
const diffHours = dayjs().diff(pastDate, 'hour');
// 计算时间差/天
const diffDays = dayjs().diff(pastDate, 'day');
let txt=''
if (diff < 2) {
txt=`刚刚`
} else if (diff < 60) {
txt=`${diff} 分钟前`
} else if (diffHours<24) {
txt=`${diffHours} 小时前`
} else if (now.diff(pastDate, 'day') === 1) {
txt=`昨天`
} else if (diffDays <5) {
txt=`${diffDays} 天前`
} else {
txt = pastDate.format('YYYY-MM-DD');
}
console.log('/day.js [88]--1','txt',txt);
return txt
}
测试代码
formatDate()
formatDate(Date.now()-1000*60*3)
formatDate('2024-07-25 13:20:00')
formatDate('2024-07-24 12:00:00')
formatDate('2024-07-21 12:00:00')
formatDate('2024-03-01 12:00:00')