封装共同方法
export function formatMsgTime(time) { //time传入的是时间戳,且时间戳长度为10位 const todayZero = new Date().setHours(0, 0, 0, 0); const yearZero = new Date(new Date().getFullYear(), 0, 1, 0, 0, 0, 0).getTime(); const target = new Date(time * 1000); const oneDay = 24 * 60 * 60 * 1000; const oneWeek = 7 * oneDay; const diff = todayZero - target.getTime(); const weekdays = ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"]; const weekday = weekdays[target.getDay()]; function formatNum(num) { return num < 10 ? '0' + num : num.toString(); } if (diff <= 0) { // 当天, return `${formatNum(target.getHours())}:${formatNum(target.getMinutes())}`; } else if (diff <= oneWeek - oneDay * 4) { // 三天内,根据需求修改需要几天内显示的是星期 return `${weekday} ${formatNum(target.getHours())}:${formatNum(target.getMinutes())}`; } else if (diff > oneWeek - oneDay * 4 && target.getTime() >= yearZero) { // 超过三天且在当年 return `${target.getMonth() + 1}/${target.getDate()} ${formatNum(target.getHours())}:${formatNum(target.getMinutes())}`; } else { //不在当年 return `${target.getFullYear()}/${target.getMonth() + 1}/${target.getDate()} ${formatNum(target.getHours())}:${formatNum(target.getMinutes())}`; } }
module.exports = {
formatMsgTime: formatMsgTime
}
标签:星期,const,target,mm,formatNum,hh,num,Date,new From: https://www.cnblogs.com/ayuaichiyu/p/18176726