优雅的格式化时间显示

在像评论列表这样的前端页面中,经常会出现时间的字段,如果显示一个标准的yyyy-MM-dd HH:mm:ss这样的时间格式,显然不是很友好,通常产品会要求显示 [1分钟前]、[刚刚] 类似的文字,那么怎么用js实现呢?我这里封装了一个通用的函数以实现,贴出完整代码:

//时间格式化
function getDateDiff(date){

    if(typeof date === 'string'){
        date = new Date(Date.parse(date.replace(/-/g, "/")));
    }else if(typeof date === 'object'){
        date = date.getTime();
    }

    var result = '',
        differentValue = new Date().getTime() - date;

    if(differentValue < 0) {
        return '穿越时空'
    }

    var minute = 1000 * 60,
        hour = minute * 60,
        day = hour * 24,
        week = day * 7,
        month = day * 30,//且都用30天算
        year = month * 12;

    if(differentValue / year >= 1){
        result = parseInt(differentValue / year) + "年前"
    }else if(differentValue / month >= 1){
        result = parseInt(differentValue / month) + "月前"
    }else if(differentValue / week >= 1){
        result = parseInt(differentValue / week) + "周前"
    }else if(differentValue / day >= 1){
        result = parseInt(differentValue / day) + "天前"
    }else if(differentValue / hour >= 1){
        result = parseInt(differentValue / hour) + "小时前"
    }else if(differentValue / minute >= 1){
        result = parseInt(differentValue / minute) + "分钟前"
    }else{
        result = "刚刚";  
    }

    return result;
}

console.log(getDateDiff('2017-06-21 20:16:24'))
console.log(getDateDiff(parseInt('1497183384000')))
console.log(getDateDiff(1497183384000))
console.log(getDateDiff(new Date('2011-01-11 20:16:24')))
console.log(getDateDiff(new Date('2017-07-14 11:43:24')))
console.log(getDateDiff(new Date('2017-07-14 20:16:24')))

控制台输出如图

posted @ 2017-07-14 14:17  微人类  阅读(524)  评论(0编辑  收藏  举报