JavaScript实现距离过去多久、刚刚、分钟、小时、天、月、时间

function formatTime(time) {
    let diff = (Date.now() - new Date(time)) / 1000,
        misuse = null,
        day = null,
        result = '';

    if (diff < 30) {
        result = '刚刚';
    } else if (diff < 3600) {
        misuse = Math.ceil(diff / 60).toString();
        misuse = ('00' + misuse).slice(misuse.length);
        result = `${misuse}分钟前`;
    } else if (diff < 3600 * 24) {
        day = Math.ceil(diff / 3600).toString();
        day = ('00' + day).slice(day.length);
        result = `${day}小时前`;
    } else if (diff < 3600 * 24 * 2) {
        result = '1天前';
    } else {
        result = '1个月前';
    }
    return result;
}

console.log(formatTime('2022-02-25 11:50:00'));
// 09分钟前
上一篇:怎么根据现有的网站文件选择空间和操作系统


下一篇:用Delphi快速计算斐波那契(Fibonacci)数列中的第n个数