js获取本周,本月,本年,上周,上月,去年的时间

function getTime(type){
  let now = new Date();
  let nowDayOfWeek = now.getDay(); //今天本周的第几天
  let nowDay = now.getDate(); //当前日
  let nowMonth = now.getMonth() + 1; //当前月  下标从0开始
  let nowYear = now.getFullYear(); //当前年
  let d = new Date(nowYear, (nowMonth + 1), 0).getDate();

  //上月
  let lastMonthDate = new Date(); //上月日期
  lastMonthDate.setDate(1);
  lastMonthDate.setMonth(lastMonthDate.getMonth()-1);
  let lastMonthYear = lastMonthDate.getFullYear();
  let lastMonth = lastMonthDate.getMonth() + 1;

  let lastYear = nowYear - 1;


  let weekStart = new Date(nowYear, nowMonth - 1, nowDay  - nowDayOfWeek + 1);
  let weekEnd = new Date(nowYear, nowMonth - 1, nowDay + (7 - nowDayOfWeek));

  let time: [string, string, string] = ["", "", "0"];
  switch (type) {
    case "0":
      break;
    //本周
    case "1":
      time = [formatDate(weekStart), formatDate(now), "4"];
      break;
    //本月
    case "2":
      let month = nowMonth < 10 ? '0' + nowMonth : nowMonth
      time = [nowYear + "-" + month + "-01", formatDate(now), "4"];
      break;
    //本年
    case "3":
      time = [nowYear + "-01-01", formatDate(now), "2"];
      break;
    //上周
    case "4":
      time = [formatDate(new Date(nowYear, nowMonth-1, nowDay - nowDayOfWeek - 6)), formatDate(new Date(nowYear, nowMonth-1, nowDay - nowDayOfWeek)), "4"];
      break;
    //上月
    case "5":
      time = [formatDate(new Date(lastMonthYear, lastMonth, 1)), formatDate(new Date(lastMonthYear, lastMonth, d)), "4"];
      break;
    //上年
    case "6":
      time = [lastYear + "-01-01", lastYear + "-12-31", "2"];
      break;
  }
  return time;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值