关注web技术发展
用心做好每一件事

js实现评论时间的转换,转化为几天前,几小时前,几分钟前,刚刚

刚写了个评论中用到,参考别人的,优化了一下,记一下。

优化内容:

1.参数由时间戳改为时间
2.处理了ios时间格式new Date()不兼容的问题

function getDateDiff(dateTime){
    let minute = 1000 * 60
    let hour = minute * 60
    let day = hour * 24
    let halfamonth = day * 15
    let month = day * 30
    let year = month * 12
    let now = new Date().getTime()
    let diffValue = now - new Date(dateTime).getTime()
    diffValue = diffValue > 0 ? diffValue : now - new Date(Date.parse(dateTime.replace(/-/g, "/"))).getTime()
    if(diffValue < 0){
        console.log('日期不合法')
    }
    let yearC = diffValue/year
    let monthC = diffValue/month
    let weekC = diffValue/(7*day)
    let dayC = diffValue/day
    let hourC = diffValue/hour
    let minC = diffValue/minute
    let result
    if(yearC >= 1){
        result = parseInt(yearC) + "年前"
    }
    else if(monthC >= 1){
        result = parseInt(monthC) + "个月前"
    }
    else if(weekC >= 1){
        result = parseInt(weekC) + "周前"
    }
    else if(dayC >= 1){
        result = parseInt(dayC) +"天前"
    }
    else if(hourC >= 1){
        result = parseInt(hourC) +"个小时前"
    }
    else if(minC>= 1){
        result = parseInt(minC) +"分钟前"
    }else
        result = "刚刚"
    return result
}

调用

console.log(getDateDiff('2017-12-15 10:05:21')) //刚刚
分享到: 更多 (0)

我要点评 抢沙发

评论前必须登录!