js格式化时间 (工具函数)
思路: 1、获取今日的年月日,不加时间(默认今日零点)
let now = new Date()
let year = now.getFullYear()
let month = now.getMonth() + 1
let date = now.getDate()
2、创建时间,获取今日事件的时间戳(不加时间默认今天零点)
let str = `${year}/${month}/${date}`
let today = new Date(str).getTime()
3、获取昨天时间的时间戳
let yesterday = new Date(str).getTime() - 1000 * 60 * 60 * 24
4、最终和目标时间做对比
整体实现如下
timeFormate(data) {
let now = new Date()
let year = now.getFullYear()
let month = now.getMonth() + 1
let date = now.getDate()
let str = `${year}/${month}/${date}`
let today = new Date(str).getTime()
let yesterday = new Date(str).getTime() - 1000 * 60 * 60 * 24
let time = new Date(data)
if (time.getTime() > today) {
return '今天 ' + time.getHours() + ':' + time.getMinutes()
} else if (time.getTime() > yesterday) {
return '昨天 ' + time.getHours() + ':' + time.getMinutes()
} else {
return (
time.getFullYear() +
'/' +
time.getMonth() +
1 +
'/' +
time.getDate() +
' ' +
time.getHours() +
':' +
time.getMinutes()
)
}
}
|