获取当前至过去及未来几个月的时间

let data = function (mounth) {
      //创建现在的时间
      let data = new Date()
      //获取年
      let year = data.getFullYear()
      //获取月
      let mon = data.getMonth() + 1
      //获取日
      let dated = data.getDate()
      //小时
      let hours = data.getHours()
      //分钟
      let minute = data.getMinutes()
      //秒
      let second = data.getSeconds()
      let arry = new Array()
      for (let i = 0; i < mounth; i++) {
        mon = mon + 1
        if (mon > 12) {
          year = year + 1
          mon = mon - 12
        }
      //过去几个月
        /*mon = mon - 1
        if (mon <= 0) {
          year = year - 1
          mon = mon + 12
        }*/
        let dating = new Date(year, mon, 0).getDate()//每个月的最后一天
        let date = dated > dating ? dating : dated//每个月的最后一天不一样,有些30,有些31
        arry[i] = year + "/" + mon + "/" + date + " " + hours + ":" + minute + ":" + second
      }
      return arry
    }
    console.log(data(2))// ["2021/1/25 13:39:11", "2021/2/25 13:39:11"]

 

posted @ 2020-12-25 13:40  王希有  阅读(218)  评论(0编辑  收藏  举报