需求分析:
1.如果是今天发表的就显示“今天”
2.如果是昨天发表的就显示“昨天”
3.如果是之前的,就计算相差的天数,然后显示“N天前”
会用到的两个函数(没有引工具,就自己手写了)
// 格式化时间 YY.MM.SS
function filterDate(str) {
var myDate = new Date(str)
var year = myDate.getFullYear()
var month = myDate.getMonth() + 1
if ( month < 10 ) {
month = '0' + month
}
var day = myDate.getDate()
if ( day < 10 ) {
day = '0' + day
}
return year + '.' + month + '.' + day
}
//格式化时间1 YY.MM.SS hh:mm
function filterDate1(str) {
const myDate = new Date(str)
const year = myDate.getFullYear()
let month = myDate.getMonth() + 1
if ( month < 10 ) {
month = '0' + month
}
let day = myDate.getDate()
if ( day < 10 ) {
day = '0' + day
}
let hour = myDate.getHours()
if ( hour < 10 ) {
hour = '0' + hour
}
let min = myDate.getMinutes()
if ( min < 10 ) {
min = '0' + min
}
return year + '.' + month + '.' + day + ' ' + hour + ':' + min
}
// 计算时间差
function getTimeDifference(preDate) {
// 今天的零点
const todayZero = new Date(new Date().setHours(0, 0, 0, 0)) / 1000
// 传来的时间
const pre = Date.parse(preDate) / 1000
const difference = (pre - todayZero)/ (60*60*24)
if (difference >= 0) {
return '今天'
} else if (difference >= -1) {
return '昨天'
} else {
return parseInt(1 - difference) + '天前'
}
}
例如:
console.log(getTimeDifference('2018-08-02T15:49:37'))

结果