js获取任意日期前一个月的所有日期

1.获取该日期(xxxx年xx月xx日)在本月的所有之前的日期,即xx月01日-xx月xx日;

2.获取该日期(xxxx年xx月xx日)上月自xx日起至月末的日期。

getLastMonthDays(date) {
  //该日期的日
  let theDay = new Date(date).getDate();
  //获取该日期的上一个月
  let lastMon = new Date(new Date(date).getTime);
  lastMon.setMonth(lastMon.getMonth());
  lastMon.setDate(0);
  //上一个月的月末日期
  let lastDayOfLastMon = lastMon.getDate();
  //该日期上一个月的起起始日期
  lastMon.setDate(theDay > lastDayOfLastMon ? lastDayOfLastMon : theDay);
  
  let day = new Date(lastMon).getDate();//日
  let month = new Date(lastMon).getMonth + 1;
  month = month < 10 ? `0${Month}` : month.toString();

  let arr = [];
  //上个月的所有日期
  if(day <= lastDayOfLastMon) {
    for(let i = day; i <= lastDayOfLastMon; i++) {
      let latsDate = month + (i < 10 ? "0" + i : i.toString())
      arr.push(latsDate)
    }
  }
  
  //本月的所有日期
  for(let j = 1; j <= theDay; j++) {
    let theMonth = new Date(date).getMonth + 1;
    theMonth = theMonth < 10 ? `0${theMonth}` : theMonth.toString();
    let theDate = theMonth + (j < 10 ? "0" + j : j.toString());
    arr.push(theDate);
  }

  return arr;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值