小程序实现微信朋友圈时间显示效果:
1分钟前,2分钟前,···,59分钟前,1小时前,2小时前,···,23小时前,一天前,2天前,2019-06-21 等等...
相关代码如下:getTime() { let start = '2019-6-21 22:41:00' let nowTime = new Date()
let oldTime = new Date(start) let diff = Math.floor((nowTime - oldTime)/1000/60) let time = start if(diff <= 59){ time = diff + '分钟前' }else if(diff <= 60*24-1){ time = Math.floor(diff / 60) + '小时前' }else if(diff <= 60*24*3-1){ time = Math.floor(diff / 60 / 24) + '天前' }else{ time = time.split(" ")[0] } return time }
实际开发过程中,会发现后台返回的数据不可能一直是 yyyy-mm-dd hh:ii:ss 格式的
也可能返回的是时间戳,这个时候会报 time.split 不是一个方法
解决方法:将时间戳或者 yyyy-mm-dd hh:ii:ss 格式 都通过js的Dete对象转换,代码如下:
getTime() { let start = '2019-6-21 22:41:00' let nowTime = new Date() let oldTime = new Date(start) let diff = Math.floor((nowTime - oldTime) / 1000 / 60) let time = start if (diff <= 59) { time = diff + '分钟前' } else if (diff <= 60 * 24 - 1) { time = Math.floor(diff / 60) + '小时前' } else if (diff <= 60 * 24 * 3 - 1) { time = Math.floor(diff / 60 / 24) + '天前' } else { // time = time.split(" ")[0] // startTime格式:yyyy-mm-dd hh:ii:ss time = this.getNowFormatDate(time) } return time } getNowFormatDate(time) { let date = new Date(time); let seperator1 = "-"; let year = date.getFullYear(); let month = date.getMonth() + 1; let strDate = date.getDate(); if (month >= 1 && month <= 9) { month = "0" + month; } if (strDate >= 0 && strDate <= 9) { strDate = "0" + strDate; } let currentdate = year + seperator1 + month + seperator1 + strDate; return currentdate; }
开发中因为不确定后台传回的是什么样的格式,因此在刚开始添加全局替换
ios不支持 “yyyy-mm-dd”,那么就替换成 “yyyy/mm/dd”
let reg=new RegExp("-"); if(reg.test(startTime)){ startTime = startTime.replace(/-/g, '/') }