显示规则:
今日 HH:mm
昨天 昨天 HH:mm
一周内 星期几 HH:mm(从6天前的0点开始算)
一周前 yy/MM/dd HH:mm
参考文章:https://segmentfault.com/a/1190000014795596?utm_source=tag-newest
代码如下:
function showTime(display){
let nowTime = new Date();//当前时间
nowYear = nowTime.getFullYear();
nowMonth = nowTime.getMonth() + 1;
nowDay = nowTime.getDate();
nowHours = nowTime.getHours();
nowMinutes = nowTime.getMinutes();
let displayTime = new Date(display);//参数时间
displayYear = displayTime.getFullYear();
displayMonth = displayTime.getMonth() + 1;
displayDay = displayTime.getDate();
displayHours = displayTime.getHours();
displayMinutes = displayTime.getMinutes();
const IN_Minutes = 3 * 60 * 1000;//3分钟
const IN_DAY = 24 * 60 * 60 * 1000;//1天
if(nowTime-displayTime <= IN_Minutes){
return '刚刚'
}else if(displayYear==nowYear && displayMonth == nowMonth && nowDay==displayDay){
return zeroize(displayHours) + ":" + zeroize(displayMinutes)
}else if(displayYear==nowYear && displayMonth == nowMonth && displayDay== nowDay-1){
return '昨天' + zeroize(displayHours) + ":" + zeroize(displayMinutes)
}else if(nowTime-displayTime<IN_DAY*7){
return getWeek(displayTime) + zeroize(displayHours) + ":" + zeroize(displayMinutes)
}else{
return displayYear + "/" + displayMonth + "/" + zeroize(displayDay) + " " + zeroize(displayHours) + ":" + zeroize(displayMinutes)
}
}
function zeroize( num ) {
return (String(num).length == 1 ? '0' : '') + num;
}
function getWeek(date) {
let week;
if(date.getDay() == 0) week = "星期日 "
if(date.getDay() == 1) week = "星期一 "
if(date.getDay() == 2) week = "星期二 "
if(date.getDay() == 3) week = "星期三 "
if(date.getDay() == 4) week = "星期四 "
if(date.getDay() == 5) week = "星期五 "
if(date.getDay() == 6) week = "星期六 "
return week;
}