javascript Date对象扩展相关function

时间:2023-03-09 00:29:28
javascript Date对象扩展相关function

本篇均以es5为主:

1,月份加减来推日期

// 根据所给月份往后推出日期
function getMonth(count) {
var date = new Date();
var year = date.getFullYear();
var month = date.getMonth();
var day = date.getDate();
// 当天日期
var getAlldays = (year, months) => {
var month = months + 1;
if (month <= 7) {
// 1-7月
if (month % 2 === 0) {
// 偶数月
if (month === 2) {
// 2月特殊
if ((year % 400 == 0) || ( year % 4 == 0 && year % 100 != 0)) {
// 闰年
var alldays = 29
} else {
var alldays = 28
}
} else {
var alldays = 30
}
} else {
// 奇数月
var alldays = 31
}
} else {
// 8-12月
if (month % 2 === 0) {
// 偶数月
var alldays = 31
} else {
var alldays = 30
}
}
return alldays
}; // 获取某年某月总天数
var fakeDate = new Date(year, month, 1); // 模拟数据,获得加完以后的月份
fakeDate.setMonth(month + count);
var newYear = fakeDate.getFullYear();
var newMonth = fakeDate.getMonth(); var requireAlldays = getAlldays(newYear, newMonth); // 加完月数以后的那个月的总天数 if (day > requireAlldays) {
// 如果当天所在日期超过加完以后月份的总天数,则推到下个月
var diff = day - requireAlldays;
return newYear + '-' + (newMonth + 2) + '-' + diff
} else {
return newYear + '-' + (newMonth + 1) + '-' + day
}
}

  

1