js 按断时间是昨天,几天前,几周前

function getDateDiff(dateTimeStamp){
    var result = '';
    var date = (new Date());
    var theDate= new Date(dateTimeStamp).getTime();
    var today = new Date(date.getFullYear(), date.getMonth(), date.getDate()).getTime(); //今天凌晨
    var yestday = new Date(today - 24*3600*1000).getTime();
    var minute = 1000 * 60;
    var hour = minute * 60;
    var day = hour * 24;
    var halfamonth = day * 15;
    var month = day * 30;
    var now = new Date().getTime();
    var diffValue = now -theDate;
    if(diffValue < 0){return;}
    var monthC =diffValue/month;
    var weekC =diffValue/(7*day);
    var dayC =diffValue/day;
    var hourC =diffValue/hour;
    var minC =diffValue/minute;
    if(monthC>=1){
        result="" + parseInt(monthC) + "月前";
    }
    else if(weekC>=1){
        result="" + parseInt(weekC) + "周前";
    }
    else if(dayC>=1){
        result=""+ parseInt(dayC) +"天前";
    }
    else if(hourC>=1){
        if(theDate< today && yestday <= theDate){
            result="昨天";
        }else{
            result=""+ parseInt(hourC) +"小时前";
        }

    }
    else if(minC>=1){
        result=""+ parseInt(minC) +"分钟前";
    }else{
        result="刚刚";
    }

    return result;
}
注意:

1:如果 dateTimeStamp 的值为 2019-12-14T20:12:33
那么此方法在ios设备上是无效的,所以需要做ios兼容
将上面方法中的

var theDate = new Date(dateTimeStamp).getTime();

替换为

    var date_stamp= dateTimeStamp.replace(/T/g,' ').replace(/[ :]/g, "-").split("-");
    var theDate = new Date(date_stamp[0], date_stamp[1]-1, date_stamp[2], date_stamp[3], date_stamp[4], date_stamp[5]);
    theDate=theDate.getTime();

如此,安卓,ios均可

你可能感兴趣的:(javascript)