js Date 日期格式化,获取距离当前时间间隔

日期格式化:

Date.prototype.format = function(fmt) {
    var o = {
        "M+": this.getMonth() + 1,
        "d+": this.getDate(),
        "h+": this.getHours(),
        "m+": this.getMinutes(),
        "s+": this.getSeconds(),
        "q+": Math.floor((this.getMonth() + 3) / 3),
        "S": this.getMilliseconds()
    };
    if (/(y+)/.test(fmt)){
        fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    }
    for (var k in o){
        if (new RegExp("(" + k + ")").test(fmt)){
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
        }
    }
    return fmt;
}

// 调用方法
var date = new Date();
date.format("yyyy-MM-dd hh:mm:ss")  // ==> "2020-04-20 16:32:31"
date.format("yyyy-MM-dd hh:mm");    // ==> "2020-04-20 16:32"
date.format("yyyy-MM-dd");          // ==> "2020-04-20"

  

距离当前时间,分为:刚刚、n分钟前、n小时前、昨天、2天前、3天前、具体日期(月-日 / 年-月-日)

function getTimeDistance(time) {
    // 支持传入10位或13位毫秒数,如 1587367194536,"1587367194"
    // 支持传入日期格式,如 "2020/4/20 15:31:18"

    if (typeof time == "number" || Number(time) == time) {
        if (String(time).length == 10) {
            time = Number(time) * 1000
        } else if (String(time).length == 13) {
            time = Number(time)
        } else {
            console.log("时间格式错误");
            return time;
        }
    } else {
        if (typeof time == "string" && time.split(" ").length == 2 && time.split(/[- : \/]/).length == 6) {
            time = new Date(time.replace(/\-/g, '/')).getTime();
        } else {
            console.log("时间格式错误");
            return time;
        }
    }

    // 处理之后的time为13位数字格式的毫秒数

    var date_now = new Date();
    var date_time = new Date(time);
    var distance = date_now.getTime() - time;

    var days = parseInt(distance / (1000 * 60 * 60 * 24));
    if (days == 1) {
        return "昨天"
    } else if (days > 1 && days < 4) {
        return days + "天前";
    } else if (days > 3) {
        // 超过3天的,返回日期,如 2018-12-05
        // 如果是今年的,就省去年份,返回 12-05
        var year = date_time.getFullYear();
        var month = date_time.getMonth() + 1;
        if (month < 10) {
            month = "0" + month;
        }
        var day = date_time.getDate();
        if (day < 10) {
            day = "0" + day;
        }
        if (date_now.getFullYear() == year) {
            return month + "-" + day;
        } else {
            return year + "-" + month + "-" + day;
        }
    }

    var hours = parseInt((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
    if (hours > 0) {
        return hours + "小时前";
    }

    var minutes = parseInt((distance % (1000 * 60 * 60)) / (1000 * 60));
    if (minutes > 0) {
        return minutes + "分钟前";
    };

    return "刚刚";
}

// 调用方法
var time = new Date("Mon Apr 18 2020 16:36:02 GMT+0800 (新加坡标准时间)").getTime();

getTimeDistance(time) // => 2天前

  

posted @ 2020-04-20 16:41  前端大兵  阅读(1938)  评论(0编辑  收藏  举报