js重写Date日期对象的add方法

来源:互联网 发布:教务系统的数据库设计 编辑:程序博客网 时间:2024/05/21 09:54
/** * 获取date所在月份的第一天。 * @returns {Date} */Date.prototype.getFirstDateOfMonth = function(){    return new Date(this.getFullYear(), this.getMonth(), 1);}/** * 获取date是月中的第几天 * @returns */Date.prototype.getDaysInMonth = function() {    var daysInMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];    var m = this.getMonth();    return m == 1 && this.isLeapYear() ? 29 : daysInMonth[m];}/** * 获取date所在月份的最后一天 * @returns {Date} */Date.prototype.getLastDateOfMonth = function() {    return new Date(this.getFullYear(), this.getMonth(), this.getDaysInMonth());}/** * 重写日期add方法 * @returns {Date} */Date.prototype.add = function(interval, value){    var d = this;    switch(interval) {        case 'milli':            d.setMilliseconds(this.getMilliseconds() + value);            break;        case 'second':            d.setSeconds(this.getSeconds() + value);            break;        case 'minute':            d.setMinutes(this.getMinutes() + value);            break;        case 'hour':            d.setHours(this.getHours() + value);            break;        case 'day':            d.setDate(this.getDate() + value);            break;        case 'month':            var day = this.getDate();            if (day > 28) {                day = Math.min(day, this.getFirstDateOfMonth().add('month', value).getLastDateOfMonth().getDate());            }            d.setDate(day);            d.setMonth(this.getMonth() + value);            break;        case 'year':            d.setFullYear(this.getFullYear() + value);            break;    }    return d;}
原创粉丝点击