<template>
<span> {{date}} </span>
</template>
<script>
export default {
name: "Time",
props:{
value:{
type:String,
default:''
}
},
data(){
return{
date:''
}
},
watch:{
value:{
handler(newV,old){
this.Time()
}
}
},
created() {
this.Time()
},
methods:{
Time(){
let timeValue = this.value
timeValue = timeValue.replace(/-/g,"/")
//封装时间
timeChange(timeValue)
this.date = timeChange(timeValue)
function timeChange (timeValue) {
timeValue = new Date(timeValue).getTime()
let timeNew = new Date().getTime() // 当前时间
// console.log('传入的时间', timeValue, timeNew)
let timeDiffer = timeNew - timeValue // 与当前时间误差
// console.log('时间差', timeDiffer)
let returnTime = ''
if (timeDiffer <= 60000) { // 一分钟内
returnTime = '刚刚'
} else if (timeDiffer > 60000 && timeDiffer < 3600000) { // 1小时内
returnTime = Math.floor(timeDiffer / 60000) + '分钟前'
} else if (timeDiffer >= 3600000 && timeDiffer < 86400000) { // 今日
// returnTime = formatTime(timeValue).substr(11, 5)
returnTime = Math.floor(timeDiffer / 3600000) + '小时前'
} else if (timeDiffer > 3600000 && isYestday(timeValue) === true) { // 昨天
returnTime = '昨天' + formatTime(timeValue).substr(11, 5)
} else if (timeDiffer > 86400000 && isYestday(timeValue) === false && isYear(timeValue) === true) { // 今年
returnTime = formatTime(timeValue).substr(5, 5)
} else if (timeDiffer > 86400000 && isYestday(timeValue) === false && isYear(timeValue) === false) { // 不属于今年
returnTime = formatTime(timeValue).substr(0, 11)
}
return returnTime
}
function formatNumber (n) {
n = n.toString()
return n[1] ? n : '0' + n
}
// 是否为今年
function isYear (timeValue) {
const dateyear = new Date(timeValue).getFullYear()
const toyear = new Date().getFullYear()
if (dateyear === toyear) {
return true
} else {
return false
}
}
// 是否为昨天
function isYestday (timeValue) {
const date = new Date(timeValue)
const today = new Date()
if (date.getFullYear() === today.getFullYear() && date.getMonth() === today.getMonth()) {
if (date.getDate() - today.getDate() === 1) {
return true
} else {
return false
}
} else {
return false
}
}
function formatTime (date) {
let t = getTimeArray(date)
return [t[0], t[1], t[2]].map(formatNumber).join('-') + ' ' + [t[3], t[4], t[5]].map(formatNumber).join(':')
}
function getTimeArray (date) {
date = new Date(date)
let year = date.getFullYear()
let month = date.getMonth() + 1
let day = date.getDate()
let hour = date.getHours()
let minute = date.getMinutes()
let second = date.getSeconds()
return [year, month, day, hour, minute, second].map(formatNumber)
}
},
}
}
</script>
<style scoped lang="less">
</style>
vue 组件封装聊天时间提示
最新推荐文章于 2024-03-06 10:39:51 发布