function newdate(a) {
var date = new Date()
var daysInMonth = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
var strYear = date.getFullYear();//年
var strMonth = date.getMonth() + 1; //月
var strDay = 1 // 日
let nub = 0//年
if (a == undefined) {
} else {
//一、解决闰年平年的二月份天数 //平年28天、闰年29天//能被4整除且不能被100整除的为闰年,或能被100整除且能被400整除
if (((strYear % 4) === 0) && ((strYear % 100) !== 0) || ((strYear % 400) === 0)) {
daysInMonth[2] = 29;
}
if (strMonth - 1 === 0) //二、解决跨年问题
{
strYear -= 1;
strMonth = 12;
}
// strDay = daysInMonth[strMonth] >= strDay ? strDay : daysInMonth[strMonth];
strDay = Math.min(strDay, daysInMonth[strMonth]);//三、前一个月日期不一定和今天同一号,例如3.31的前一个月日期是2.28;9.30前一个月日期是8.30
a = a ? a : 0
console.log(strMonth,'我是月份')
if (strMonth < 10)//给个位数的月、日补零
{
strMonth = "0" + strMonth;
console.log('走了吗',strMonth)
}
if (strDay < 10) {
strDay = "0" + strDay;
console.log('走了吗11111',strDay)
}
var yue = strMonth //月
if (a >= 12) {
nub = Math.floor(a / 12)
let yuenub = a % 12
yue -= yuenub
} else {
yue -= a;
if(yue<10){
yue='0'+yue
}
console.log(yue,'yueeee')
}
}
nub = nub ? nub : 0
yue = yue ? yue : strMonth
var datastr = (strYear - nub) + "-" + (yue) + "-" + strDay + '至' + strYear + '-' + (strMonth) + "-" + daysInMonth[strMonth.length > 1 ? Number(strMonth.substr(1)) : strMonth]
console.log(datastr);
return datastr;
}
newdate()这个括号里面传的值作为依据:如果不传就是本月1号到本月31号;传1就是上月1号到上个月31号;传2就是上上个月1号到上个月31号。
在这里不用担心每个月有30号,31号之类的都做了处理