js 处理日期相关操作 Date.format

 


/**
 * 日期格式化: var dateStr ="1993-11-11 11:11:11";
 *     var date = new Date(dateStr.replace(/-/g, '/'));  //兼容ie浏览器
 *     date.format("HH:mm:ss");
 *     date.format("yyyy-MM-dd");
 *     date.format("yyyy-MM-dd HH:mm:ss");
 *     date.format("yyyy年MM月dd日");
 *     date.format("yyyy年MM月dd日 HH时mm分ss秒");
 */
if (!Date.prototype.format) {
Date.prototype.format = function (format) {
    var o = {
        "M+": this.getMonth() + 1, //month
        "d+": this.getDate(), //day
        "h+": this.getHours(), //hour
        "m+": this.getMinutes(), //minute
        "s+": this.getSeconds(), //second
        "q+": Math.floor((this.getMonth() + 3) / 3), //quarter
        "S": this.getMilliseconds() //millisecond
    }

    if (/(y+)/.test(format)) {
        format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    }

    for (var k in o) {
        if (new RegExp("(" + k + ")").test(format)) {
            format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
        }
    }
    return format;
}
}
;

Date.prototype.addDays = function (d) {
    this.setDate(this.getDate() + d);
    return this;
};
Date.prototype.addWeeks = function (w) {
    this.addDays(w * 7);
    return this;
};

Date.prototype.addMonths = function (m) {
    var d = this.getDate();
    this.setMonth(this.getMonth() + m);
    if (this.getDate() < d) {
        this.setDate(0);
    }
    return this;
};
Date.prototype.addYears = function (y) {
    var m = this.getMonth();
    this.setFullYear(this.getFullYear() + y);
    if (m < this.getMonth()) {
        this.setDate(0);
    }
    return this;
};

/**
 * 计算日期间隔
 * @param strInterval
 * @param dtEnd
 * @returns {*}
 * @constructor
 */
if (!Date.prototype.DateDiff) {
    Date.prototype.DateDiff = function (strInterval, dtEnd) {
        var dtStart = this;
        if (typeof dtEnd == 'string') {
            dtEnd = StringToDate(dtEnd);
        }
        switch (strInterval) {
            case 's':
                return parseInt((dtEnd - dtStart) / 1000);
            case 'n':
                return parseInt((dtEnd - dtStart) / 60000);
            case 'h':
                return parseInt((dtEnd - dtStart) / 3600000);
            case 'd':
                return parseInt((dtEnd - dtStart) / 86400000);
            case 'w':
                return parseInt((dtEnd - dtStart) / (86400000 * 7));
            case 'm':
                return (dtEnd.getMonth() + 1) + ((dtEnd.getFullYear() - dtStart.getFullYear()) * 12) - (dtStart.getMonth() + 1);
            case 'y':
                return dtEnd.getFullYear() - dtStart.getFullYear();
        }
    }
};

 

你可能感兴趣的:(前端学习,js)