仿微信时间日期格式:
刚刚、x小时前、x天前
const formatTime = date => {
const year = date.getFullYear()
const month = date.getMonth() + 1
const day = date.getDate()
const hour = date.getHours()
const minute = date.getMinutes()
const second = date.getSeconds()
return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}
const formatNumber = n => {
n = n.toString()
return n[1] ? n : '0' + n
}
const formatTimeName = date => {
const t = date.getTime()
const now = new Date()
const tn = now.getTime()
const difft = (tn - t)/1000
if(difft<10){
return '刚刚'
}
const s = 60
if (difft < s) {
return Math.floor(difft) + '秒前'
}
const h = 3600
if(difft<h){
return Math.floor(difft/s) + '分钟前'
}
const d = 3600*24
if(difft<d){
return Math.floor(difft/h) + '小时前'
}
const w = 3600*24*7
const td = Math.floor(difft / d)
if(difft<w){
return td + '天前'
}
if (now.getFullYear() === date.getFullYear()){
return [date.getMonth() + 1, date.getDate()].map(formatNumber).join('-') + ' ' + [date.getHours(), date.getMinutes()].map(formatNumber).join(':')
}
return formatTime(date)
}
网友评论