日期格式化显示为刚刚、1分钟前等

例如

console.log(showtime(new Date()));

var date = new Date();
date.setHours(date.getHours() -3);
console.log(showtime(date));

输出

刚刚
3小时前

代码实现如下:

/**
 * 格式化日期 刚刚/*小时前等
 * 
 * @param date 时间戳 / new Date()
 * @returns {string|string|boolean}
 */
export function showtime(date) {
    if(typeof date === "number") {
        date = new Date(date);
    }
    let diff = (new Date().getTime() - date.getTime()) / 1000;
    let dayDiff = Math.floor(diff / 86400);
    
    const formatDate = function (date) {
        let today = new Date(date);
        let year = today.getFullYear();
        let month = ("0" + (today.getMonth() + 1)).slice(-2);
        let day = ("0" + today.getDate()).slice(-2);
        let hour = today.getHours();
        let minute = today.getMinutes();
        let second = today.getSeconds();
        return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
    };

    if (isNaN(dayDiff) || dayDiff < 0 || dayDiff >= 31) {
        return formatDate(date);
    }
    return (
        (dayDiff === 0 &&
            ((diff < 60 && "刚刚") ||
                (diff < 120 && "1分钟前") ||
                (diff < 3600 && Math.floor(diff / 60) + "分钟前") ||
                (diff < 7200 && "1小时前") ||
                (diff < 86400 && Math.floor(diff / 3600) + "小时前"))) ||
        (dayDiff === 1 && "昨天") ||
        (dayDiff < 7 && dayDiff + "天前") ||
        (dayDiff < 31 && Math.ceil(dayDiff / 7) + "周前")
    );
}

更新日期:
作者: qwding