JS获取当前日期,获取上个月的日期,一个月有多少天

小程序、H5 获取日期

  // 获取时间不满两位补0
  formatTen: function (num) {
    return num > 9 ? (num + "") : ("0" + num);
  },
   // 当前日期
  nowData: function () {
    let curDate = new Date();
    let curYear = curDate.getFullYear();  //获取完整的年份(4位,1970-????)
    let curMonth = curDate.getMonth() + 1;  //获取当前月份(0-11,0代表1月,所以要加1)
    let curDay = curDate.getDate();       //获取当前日(1-31)
    let time = curYear + '-' + this.formatTen(curMonth) + '-' + this.formatTen(curDay);
    //取上一个月,curYear 表示当前年 ,curMonth 表示当前月份
    let year2 = curYear
    let month2 = curMonth
    if (parseFloat(curMonth) - 1 == 0) {
      month2 = 12;
      year2 = curYear - 1;
    } else {
      year2 = curYear
      month2 = this.formatTen(parseFloat(curMonth) - 1)
    }
    this.setData({
      lastTime: this.getMonthDay(year2, month2),   //上个月一共有多少天
      beginReportTime: year2 + '-' + month2,   //上个月的日期  
    })

  },
    // 一个月有多少天 year年 ,month月
  getMonthDay: function (year, month) {
    let days = new Date(year, month, 0).getDate()
    return days
  },

猜你喜欢

转载自blog.csdn.net/weixin_41760500/article/details/104692793