在消息列表中我们经常会要求展示过去时间,通常是显示秒、分、时间、日期等
于是自己动手写了个方法实现功能,需要的可以直接复制了
function rexTime(timestamp) {
if(!timestamp) return timestamp;
let stamp = new Date(timestamp);
let diffTime = Math.floor((Date.now() - stamp.getTime()) / 1000);
if (diffTime < 3600) {
if (diffTime < 60) {
return diffTime + '秒前';
}
return Math.floor(diffTime / 60) + '分钟前';
} else {
const nowFirst = new Date().setHours(0, 0, 0, 0);
const beforeWeek = new Date().setDate(new Date().getDate() - 7);
const yesterday = new Date(nowFirst - 86400000).getTime();
const stampNums = stamp.getTime();
const stampHours = stamp.getHours() < 10 ? '0' + stamp.getHours() : stamp.getHours();
const stampMinutes = stamp.getMinutes() < 10 ? '0' + stamp.getMinutes() : stamp.getMinutes();
if (stampNums > nowFirst) {
return `${stampHours}:${stampMinutes}`;
} else if (stampNums < nowFirst && yesterday <= stampNums) {
return `昨天${stampHours}:${stampMinutes}`;
} else if (beforeWeek < stampNums) {
const weekData = ['日', '一', '二', '三', '四', '五', '六'];
const stampWeeks = stamp.getDay();
return `星期${weekData[stampWeeks]} ${stampHours}:${stampMinutes}`;
} else {
const stampYears = stamp.getFullYear();
const stampMonths = stamp.getMonth() + 1 < 10 ? '0' + stamp.getMonth() + 1 : stamp.getMonth() + 1;
const stampDates = stamp.getDate() < 10 ? '0' + stamp.getDate() : stamp.getDate();
const nowYears = new Date().getFullYear();
return `${stampYears === nowYears ? '' : stampYears.toString().substring(2, 4) + '年'}${stampMonths}月${stampDates}日`;
}
}
}
觉得不错的话点个赞吧!