js获取时间,格式化时间,获取时间范围,输出开始时间和结束时间

开箱即用的时间格式化方法

输出格式先看下

//一年
// {"start": "2022","end": "2023"}
//两个月
// {"start": "2023-09","end": "2023-11"}
//3天
// {"start": "2023-11-19","end": "2023-11-22"}

接下来直接附上封装好的方法,不用做改动,直接在script标签中就可以在控制台输出上面格式的时间了,最下面有使用方法,包括传参规范

    Date.prototype.format = (format)=> {
    
    
        if (format == undefined || format == "")format = "yyyy/MM/dd";
        var o = {
    
    
          "M+": this.getMonth() + 1, // month
          "d+": this.getDate(), // day
          "h+": this.getHours(), // hour
          "m+": this.getMinutes(), // minute
          "s+": this.getSeconds(), // secondAlarm
          "q+": Math.floor((this.getMonth() + 3) / 3), // quarter
          S: this.getMilliseconds(), // millisecond
        };
        if (/(y+)/.test(format))format = format.replace(RegExp.$1,(this.getFullYear() + "").substr(4 - RegExp.$1.length));
        for (var k in o) {
    
    
          if (new RegExp("(" + k + ")").test(format))format = format.replace(RegExp.$1,RegExp.$1.length == 1? o[k]: ("00" + o[k]).substr(("" + o[k]).length));
        }
        return format;
      };
      var  getDateRange=(type, formatter, num)=>{
    
    
        if (!formatter)formatter = "yyyy-MM-dd";
        if (!num) num = 1;
        let nowDate = new Date();
        let start = null;
        let end = nowDate.format(formatter);
        switch (type) {
    
    
          case "year":
            start = new Date(
              nowDate.getFullYear() - 1 * num,
              nowDate.getMonth(),
              nowDate.getDate(),
              0,
              0,
              0
            ).format(formatter);
            break;
          case "month":
            start = new Date(
              nowDate.getTime() - 1000 * 3600 * 24 * 30 * num
            ).format(formatter);
            break;
          case "week":
            start = new Date(
              nowDate.getTime() - 1000 * 3600 * 24 * 7 * num
            ).format(formatter);
            break;
          case "day":
            start = new Date(nowDate.getTime() - 1000 * 3600 * 24 * num).format(
              formatter
            );
            break;
          default:
            start = end;
            break;
        }
        let range = {
    
    
          start: start,
          end: end,
        };
        return range;
      }
      /**
       * 获取查询时间范围
       * @param type:“year”——年;“month”——月;;“day”——天
       * @param formatter:日期格式,不传则默认为“yyyy-MM-dd”
       * @param num:倍数,不传则默认为1,即1年/1月/1天
       * @returns {start:1年/月/天之前, end:当前日期}
       */
      console.log(getDateRange("year", "yyyy", 1));
      // {"start": "2022","end": "2023"}
      console.log(getDateRange("month", "yyyy-MM", 2));
      // {"start": "2023-09","end": "2023-11"}
      console.log(getDateRange("day", "yyyy-MM-dd", 3));
      // {"start": "2023-11-19","end": "2023-11-22"}

记得关注哦,双击么么哒!!!

猜你喜欢

转载自blog.csdn.net/m0_71585401/article/details/134553323