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

js获取本周,本月,本年

程序员文章站 2022-06-15 22:50:45
...
    // 计算当周
    function getDates() {
      var data = new Date();
      var timesStamp = data.getTime();
      console.log(timesStamp)
      var currenDay = data.getDay();
      var dates = [];

      for (var i = 0; i < 7; i++) {
        dates.push(
          new Date(
            timesStamp + 24 * 60 * 60 * 1000 * (i - ((currenDay + 6) % 7)))
            .toLocaleDateString()
        );
      }

      return dates
    };

    //计算当月
    function ThisMonth() {
      var date = new Date();
      var year = date.getFullYear();
      var month = date.getMonth();

      var min = new Date(year, month, 1);
      var max = new Date(year, month + 1, 0);


      return [formatDateTime(min, 'YYYYMMDD'), formatDateTime(max, 'YYYYMMDD')]

    };

    // 获取本年
    function ThisYear() {
      var firstDay = new Date();
      firstDay.setDate(1);
      firstDay.setMonth(0);
      var lastDay = new Date();
      lastDay.setFullYear(lastDay.getFullYear() + 1);
      lastDay.setDate(0);
      lastDay.setMonth(-1);

      firstDay = formatDateTime(firstDay, 'YYYYMMDD');
      lastDay = formatDateTime(lastDay, 'YYYYMMDD');

      return [firstDay, lastDay];
    };


    //日期格式化
    function formatDateTime(time, format, YMSign = '-', HSSign = ':') {
      let formatDate = '';
      function add0(num) {
        return num >= 10 ? num : '0' + num;
      }
      let date = new Date(time);
      let year = date.getFullYear();
      let mounth = add0(date.getMonth() + 1);
      let day = add0(date.getDate());
      let hours = add0(date.getHours());
      let minutes = add0(date.getMinutes());
      let seconds = add0(date.getSeconds());
      switch (format) {
        case 'YYYY':
          formatDate = `${year}`;
          break;
        case 'YYYY-MM':
          formatDate = `${year}${YMSign}${mounth}`;
          break;
        case 'YYYYMM':
          formatDate = `${year}${mounth}`;
          break;
        case 'YYYY-MM-DD':
          formatDate = `${year}${YMSign}${mounth}${YMSign}${day}`;
          break;
        case 'YYYYMMDD':
          formatDate = `${year}${mounth}${day}`;
          break;
        case 'YYYY-MM-DD HH:MM:SS':
          formatDate = `${year}${YMSign}${mounth}${YMSign}${day} ${hours}${HSSign}${minutes}${HSSign}${seconds}`;
          break;
        default:
          formatDate = `${year}${YMSign}${mounth}${YMSign}${day}T${hours}${HSSign}${minutes}${HSSign}${seconds}`;
      }
      return formatDate;
    }