js获取本月第一天和最后一天日期,上个月第一天和最后一天日期

本月第一天和最后一天的日期

//本月第一天和最后一天日期
getCurDay(){
  let nowdays = new Date();
  let year = nowdays.getFullYear();
  let month = nowdays.getMonth() + 1;
  month = month > 9 ? month : "0" + month;

  let firstDayOfCurMonth = `${year}-${month}-01`;
  let lastDay = new Date(year, month, 0);
  let lastDayOfCurMonth = `${year}-${month}-${lastDay.getDate()}`;

  console.log(firstDayOfCurMonth)
  console.log(lastDayOfCurMonth)
}

上月第一天和最后一天的日期

//上月第一天和最后一天日期
getPreDay() {
  let nowdays = new Date();
  let year = nowdays.getFullYear();
  let month = nowdays.getMonth();
  if (month == 0) {
    month = 12;
    year = year - 1;
  }
  month = month > 9 ? month : "0" + month;
  let firstDayOfPreMonth = `${year}-${month}-01`;
  let lastDay = new Date(year, month, 0);
  let lastDayOfPreMonth = `${year}-${month}-${lastDay.getDate()}`;

  console.log(firstDayOfPreMonth)
  console.log(lastDayOfPreMonth)

}

在这里插入图片描述
参考文章:https://blog.csdn.net/weixin_42283981/article/details/87976273

格式化日期

// 格式化日期
 getFullDate(targetDate) {
   var D, y, m, d;
   if (targetDate) {
     D = new Date(targetDate);
     y = D.getFullYear();
     m = D.getMonth() + 1;
     d = D.getDate();
   } else {
     y = fullYear;
     m = month;
     d = date;
   }
   m = m > 9 ? m : "0" + m;
   d = d > 9 ? d : "0" + d;
   return y + "-" + m + "-" + d;
 },

你可能感兴趣的:(js)