欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

JS获取前一个月时间(代码实例)

程序员文章站 2022-04-15 10:36:50
js获取前一个月时间(代码实例) 找了很久没找到,干脆自己写一个。 function getpremonthdate() { let times = new date();...

js获取前一个月时间(代码实例)

找了很久没找到,干脆自己写一个。
  
function getpremonthdate() {  
  let times = new date();  
  let y = times.getfullyear();  
  let m = times.getmonth() + 1;  
  let d = times.getdate();  
  let md = "";  
  let datearr = [];  
  for (let i = 0; i <= 30; i++) {  
    if (d - i > 0) {  
      md = m + "/" + (d - i);  
      datearr[i] = md;  
    } else {  
      m = times.getmonth();  
      if (m == 1 || m == 3 || m == 5 || m == 7 || m == 8 || m == 10 || m == 12) {  
        md = m + "/" + (d - i + 31);  
      } else if (m == 4 || m == 6 || m == 9 || m == 11) {  
        md = m + "/" + (d - i + 30);  
      } else {  
        if (((y % 4) == 0) && ((y % 100) != 0) || ((y % 400) == 0)) {   //闰年  
          md = m + "/" + (d - i + 29);  
        } else {  
          md = m + "/" + (d - i + 28);  
        }  
      }  
      datearr[i] = md;  
    }  
  }  
  console.log(datearr);  
}  
getpremonthdate();  
  
//结果是否你想要的呢?  
  
/*[ '5/19',  
  '5/18',  
  '5/17',  
  '5/16',  
  '5/15',  
  '5/14',  
  '5/13',  
  '5/12',  
  '5/11',  
  '5/10',  
  '5/9',  
  '5/8',  
  '5/7',  
  '5/6',  
  '5/5',  
  '5/4',  
  '5/3',  
  '5/2',  
  '5/1',  
  '4/30',  
  '4/29',  
  '4/28',  
  '4/27',  
  '4/26',  
  '4/25',  
  '4/24',  
  '4/23',  
  '4/22',  
  '4/21',  
  '4/20',  
  '4/19' ] */