js自然年月的加减函数

varTimeUtils = ({

getOffsetYear: function (beginDate, XYear) {

return this.getOffsetMonth(beginDate, XYear * 12);

},

getOffsetMonth: function (beginDate, XMonth) {

var matrix = beginDate.substr(0, 10).split("-");

var year = matrix[0] * 1;

var month = matrix[1] * 1;

var day = matrix[2] * 1;

var newMonth = month + XMonth;

if (newMonth > 12 || newMonth < 1) {

year += newMonth / 12;

newMonth = newMonth % 12;

if (newMonth === 0) {

year--;

newMonth = 12;

}

}

var newDay = day;

if ((newDay > this.getLastDayOfMonth(year, newMonth)) || (day === this.getLastDayOfMonth(year, month) )) {

newDay = this.getLastDayOfMonth(year, newMonth);

}

var date = new Date(year, newMonth - 1, newDay);

return date.format("yyyy-MM-dd");

},

getEndXYear: function (beginDate, XYear) {

return this.getEndXMonth(beginDate, XYear * 12);

},

getEndXMonth: function (beginDate, XMonth) {

var matrix = beginDate.substr(0, 10).split("-");

var year = matrix[0] * 1;

var month = matrix[1] * 1;

var day = matrix[2] * 1;

var newMonth = month + XMonth;

if (newMonth > 12 || newMonth < 1) {

year += newMonth / 12;

newMonth = newMonth % 12;

if (newMonth === 0) {

year--;

newMonth = 12;

}

}

var newDay = day - 1;

if (newDay > this.getLastDayOfMonth(year, newMonth)) {

newDay = this.getLastDayOfMonth(year, newMonth);

}

var date = new Date(year, newMonth - 1, newDay);

return date.format("yyyy-MM-dd");

},

getLastDayOfMonth: function (year, month) {

year = year * 1;

month = month * 1;

//大月

var day = 31;

//小月

if (month === 4 || month === 6 || month === 9 || month === 11) {

day = 30

}

//2月

else if (month === 2) {

if (((year % 4) === 0) && ((year % 100) !== 0) || ((year % 400) === 0)) {

day = 29

} else {

day = 28

}

}

return day;

},

//判断是否为闰年

isLeapYear: function (year) {

year = year * 1;

if (((year % 4) === 0) && ((year % 100) !== 0) || ((year % 400) === 0)) {

return (true);

} else {

return (false);

}

},

})

你可能感兴趣的:(js自然年月的加减函数)