【js】格式化时间,获取 今日/昨日/本月/上个月/最近一周/最近一月 时间

function dateFormat(dateVal, fmt = "YYYY-mm-dd HH:MM:SS") {
        dateVal = dateVal || Date.now();
        const date = new Date(dateVal);
        let ret;
        const opt = {
          "Y+": date.getFullYear().toString(), // 年
          "m+": (date.getMonth() + 1).toString(), // 月
          "d+": date.getDate().toString(), // 日
          "H+": date.getHours().toString(), // 时
          "M+": date.getMinutes().toString(), // 分
          "S+": date.getSeconds().toString() // 秒
        };
        for (let k in opt) {
          ret = new RegExp("(" + k + ")").exec(fmt);
          if (ret) {
            fmt = fmt.replace(
              ret[1],
              ret[1].length == 1 ? opt[k] : opt[k].padStart(ret[1].length, "0")
            );
          }
        }

        return fmt;
      }

      console.log("=== dateFormat():", dateFormat());
      //   const hourVal = 1000 * 60 * 60;
      const day0 = new Date(new Date().toLocaleDateString()).getTime();
      // 月初
      const m0 = new Date().setDate(1);
      // 月末
      const m9 = new Date(m0);
      m9.setMonth(new Date().getMonth() + 1);
      m9.setDate(0);

      // 上个月
      const mS0 = new Date(m0);
      mS0.setMonth(new Date().getMonth() - 1);
      mS0.setDate(1);

      const mS1 = new Date(mS0);
      mS1.setMonth(new Date().getMonth());
      mS1.setDate(0);

      console.info(
        "最近一小时===",
        dateFormat(new Date() - 1000 * 60 * 60),
        dateFormat()
      );
      console.info(
        "今日===",
        dateFormat(new Date(new Date().toLocaleDateString()).getTime()),
        dateFormat(
          new Date(new Date().toLocaleDateString()).getTime() +
            1000 * 60 * 60 * 24 -
            1000
        )
      );
      console.info(
        "昨日===",
        dateFormat(day0 - 1000 * 60 * 60 * 24),
        dateFormat(day0 - 1000)
      );
      console.info("本月===", dateFormat(m0), dateFormat(m9));
      console.info("上个月===", dateFormat(mS0), dateFormat(mS1));
      console.info(
        "最近一周===",
        dateFormat(new Date() - 1000 * 60 * 60 * 24 * 7),
        dateFormat()
      );
      console.info(
        "最近一月===",
        dateFormat(new Date() - 1000 * 60 * 60 * 24 * 31),
        dateFormat()
      );
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值