直接上代码吧
里面并没有显示秒数,可以根据自己需要来进行修改。
格式大概如下方注释所示。
//时间戳转时间
function timeStampToTime(stamp){
if(stamp.length==10) stamp = Number(stamp+'000')
if(typeof stamp != 'number') stamp = Number(stamp)
const ut = new Date(stamp) //updateTime 简称ut吧
const now = new Date()
const utYear = ut.getFullYear()
const utMonth = ('0'+(ut.getMonth()+1)).slice(-2)
const utDate = ('0'+(ut.getDate())).slice(-2)
const utHour = ('0'+ut.getHours()).slice(-2)
const utMinute = ('0'+ut.getMinutes()).slice(-2)
const nowYear = now.getFullYear()
const nowMonth = ('0'+(now.getMonth()+1)).slice(-2)
//一分钟内 例:`57秒前`
if(now - ut<60000) return `${parseInt((now - ut)/1000)}秒前`
//1小时之内 例:`57分钟前`
if(now - ut<3600000) return `${parseInt((now - ut)/1000/60)}分钟前`
//24小时内 例:`15小时前`
if(now - ut<86400000) return `${parseInt((now - ut)/1000/60/60)}小时前`
//昨天 例:`昨天 15:32`
if(now - ut<172800000) return `昨天 ${utHour}:${utMinute}`
//七天内 例:`3天前`
if(now - ut<604800000) return `${parseInt((now - ut)/1000/60/60/24)}天前 ${utHour}:${utMinute}`
//一个月内 例:`15 09:32`
if(nowYear == nowYear && utMonth == nowMonth) return `${utDate*1}号 ${utHour}:${utMinute}`
//一年内 例:`09-15 9:32`
if(utYear == nowYear) return `${utMonth}-${utDate} ${utHour}:${utMinute}`
//例:`2022-09-15 9:32`
return `${utYear}-${utMonth}-${utDate} ${utHour}:${utMinute}`
}