编程语言
首页 > 编程语言> > JavaScript实现距离过去多久、刚刚、分钟、小时、天、月、时间

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分钟前

标签:3600,多久,JavaScript,分钟,result,misuse,diff,else,day
来源: https://blog.csdn.net/weixin_51157081/article/details/123130143