获取本月、上月、下月的起始日、结束日 (不传或0代表本月,-1代表上月,1代表下月)

/**获取本月、上月、下月的起始日、结束日 (不传或0代表本月,-1代表上月,1代表下月)*/
// 1.调用方法 getMonth("s",0)、getMonth("e",0)
// 2.type 为"s"代表开始日期,type为"e"代表结束日期
// 3.dates  不传或0代表本月,-1代表上月,1代表下月
export const getMonth = (type, months) => {
  var d = new Date();
  var year = d.getFullYear();
  var month = d.getMonth() + 1;
  if (Math.abs(months) > 12) {
      months = months % 12;
  };
  if (months != 0) {
      if (month + months > 12) {
          year++;
          month = (month + months) % 12;
      } else if (month + months < 1) {
          year--;
          month = 12 + month + months;
      } else {
          month = month + months;
      };
  };
  month = month < 10 ? "0" + month: month;
  var date = d.getDate();
  var firstday = year + "-" + month + "-" + "01";
  var lastday = "";
  if (month == "01" || month == "03" || month == "05" || month == "07" || month == "08" || month == "10" || month == "12") {
      lastday = year + "-" + month + "-" + 31;
  } else if (month == "02") {
      if ((year % 4 == 0 && year % 100 != 0) || (year % 100 == 0 && year % 400 == 0)) {
          lastday = year + "-" + month + "-" + 29;
      } else {
          lastday = year + "-" + month + "-" + 28;
      };
  } else {
      lastday = year + "-" + month + "-" + 30;
  };
  var day = "";
  if (type == "s") {
      day = firstday;
  } else {
      day = lastday;
  };
  return day;
}

 

posted @ 2023-06-20 16:05  琼菇凉  阅读(103)  评论(0编辑  收藏  举报