获取前两个月,上个月的开始日期和结束日期

该JavaScript函数newdate(a)主要用于计算指定月份数之前的日期范围。它考虑了闰年和平年的二月份天数,处理了跨年问题,并确保输出的日期格式正确。当不传参数时,返回当前月的日期范围;传入1则返回上一月的日期范围,依此类推。
摘要由CSDN通过智能技术生成

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号之类的都做了处理

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值