import dayjs from 'dayjs'
// 多久之前
export const getTime = (dateTimeStamp) => {
const before = new Date(dateTimeStamp).getTime()
const minute = 1000 * 60;
const hour = minute * 60;
const day = hour * 24;
const month = day * 30;
// const year = month * 12
const now = new Date().getTime();
const timeDiff = now - before;
// dateTimeStamp存在
if (before <= 0) return
if(timeDiff < 0) return
// const yearBefore = timeDiff / year
const monthBefore = timeDiff / month // 几个月
// const weekBefore =timeDiff / (7 * day) // 几周
const dayBefore =timeDiff / day // 几天
const hourBefore =timeDiff / hour // 小时
// const minBefore =timeDiff / minute // 分钟
if (monthBefore > 1) {// 大于一个月 显示年月日
return dayjs(dateTimeStamp).format('YYYY年MM月DD日')
}
// else if(monthBefore>=1) {
// return "" + parseInt(monthBefore) + "月前"
// }
// else if(weekBefore >= 1) {
// return "" + parseInt(weekBefore) + "周前"
// }
else if(dayBefore>=1) {
return ""+ parseInt(dayBefore) +"天前"
}
else if(hourBefore>=1) {
return ""+ parseInt(hourBefore) +"小时前"
}
// else if(minBefore>=1) {
// return ""+ parseInt(minBefore) +"分钟前"
// }
else
return "刚刚"
}
// 格式化时间
export const getSpecificTime = (val) => {
return dayjs(val).format('YYYY年MM月DD日 HH:mm')
}
// 使用
import { getTime } from '@/services/time'
computed: {
timer() {
return getTime(this.data.dateTime)
},
},
<div> {{ timer }}</div>
时间格式化,显示一周前,一月前,刚刚
最新推荐文章于 2024-05-08 09:48:00 发布