const formatDateTime = (dateJson: string)=> {
let date = new Date(Number(dateJson)* 1000);
let y = date.getFullYear();
let m: number | string = date.getMonth() + 1;
m = m < 10 ? ('0' + m) : m;
let d: number | string = date.getDate();
d = d < 10 ? ('0' + d) : d;
let h: number | string = date.getHours();
h = h < 10 ? ('0' + h) : h;
let minute: number | string = date.getMinutes();
minute = minute < 10 ? ('0' + minute) : minute;
let second: number | string = date.getSeconds();
second = second < 10 ? ('0' + second) : second;
let nowDate = new Date();
let yNow = nowDate.getFullYear();
let mNow: number | string = nowDate.getMonth() + 1;
mNow = mNow < 10 ? ('0' + mNow) : mNow;
let dNow: number | string = nowDate.getDate();
dNow = dNow < 10 ? ('0' + dNow) : dNow;
let hNow: number | string = nowDate.getHours();
hNow = hNow < 10 ? ('0' + hNow) : hNow;
let minuteNow: number | string = nowDate.getMinutes();
minuteNow = minuteNow < 10 ? ('0' + minuteNow) : minuteNow;
let secondNow: number | string = nowDate.getSeconds();
secondNow = secondNow < 10 ? ('0' + secondNow) : secondNow;
return yNow === y && m === mNow && Math.abs(Number(dNow) - Number(d)) < 10 && Math.abs(Number(dNow) - Number(d)) > 0 ?
Math.abs(Number(dNow) - Number(d)) + "天前"
: yNow === y && m === mNow && dNow === d && Math.abs(Number(hNow) - Number(h)) < 24 && Math.abs(Number(hNow) - Number(h)) > 0 && Math.abs(Number(minuteNow) - Number(minute)) > 59?
Math.abs(Number(hNow) - Number(h)) + "小时前" :
yNow === y && m === mNow && dNow === d && Math.abs(Number(hNow) - Number(h)) < 24 && Math.abs(Number(minuteNow) - Number(minute)) < 59&&Math.abs(Number(minuteNow) - Number(minute)) > 0?
Math.abs(Number(minuteNow) - Number(minute)) + "分钟前":
yNow === y && m === mNow && dNow === d && hNow === h ? "刚刚" : y + '-' + m + '-' + d
};
时间戳动态处理成(刚刚,几分钟前、几天前……)
于 2024-03-25 13:51:08 首次发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)