var date_list = [];
//第一个参数传递日期,第二个参数传递num,及要返回最近的年月, 第三个参数传递一个数组用于保存日期,第四个参数固定不变
getLastMonthYestdy(new Date(),6, date_list, true);
// console.log(date_list);
$scope.dateTypeList = date_list;
$scope.dateType = $scope.dateTypeList[0];
//获取最近六个月的日期如 ["2019年04月", "2019年03月", "2019年02月", "2019年01月", "2018年12月", "2018年11月"]
function getLastMonthYestdy(da, num, date_list, flag) {
var date = new Date(da);
var daysInMonth = new Array([0], [31], [28], [31], [30], [31], [30], [31], [31], [30], [31], [30], [31]);
var strYear = date.getFullYear();
var strDay = date.getDate();
var strMonth = date.getMonth() + 1;
if (flag === true){
strMonth = strMonth > 9 ? strMonth : "0"+strMonth;
var str = strYear+"年"+strMonth+"月";
date_list.push(str);
}
if (strYear % 4 === 0 && strYear % 100 !== 0) {//一、解决闰年平年的二月份天数 //平年28天、闰年29天//能被4整除且不能被100整除的为闰年
daysInMonth[2] = 29;
}
if (strMonth - 1 === 0) //二、解决跨年问题
{
strYear -= 1;
strMonth = 12;
} else {
strMonth -= 1;
}
// strDay = daysInMonth[strMonth] >= strDay ? strDay : daysInMonth[strMonth];
strDay = Math.min(strDay, daysInMonth[strMonth]); //三、前一个月日期不一定和今天同一号,例如3.31的前一个月日期是2.28;9.30前一个月日期是8.30
//给个位数的月、日补零
if (strMonth < 10){
strMonth = "0" + strMonth;
}
if (strDay < 10) {
strDay = "0" + strDay;
}
var datastr = strYear + "-" + strMonth + "-" + strDay;
var datastr1 = strYear.toString() + "年" + strMonth.toString() + "月";
date_list.push(datastr1);
num -= 1;
if (num > 1){
getLastMonthYestdy(datastr, num, date_list, false)
}
}
JavaScript获取最近几个月的年月
最新推荐文章于 2024-07-18 11:50:26 发布