获取上一年份最后七周的开始和结束日期

function getsevenWeekdate() {
  // 先拿现在时间
  var now = new Date();
  // 拿到去年最后一天和六周前的那天
  var lastDay = new Date(now.getFullYear() - 1 + "-12-31");
  var firstDay = new Date(lastDay.getTime() - 1000*60*60*24*7*6);
  // 获取去年最后一天的星期
  var week = lastDay.getDay();
  // 如果不是周日
  if (week != 0) {
    // 最后一天是一周天数减当前星期
    lastDay = now.getFullYear() + '-01-' + (7 - week);
    // 如果是周一
    if (week == 1) {
      var fy = firstDay.getFullYear();
      var fm = firstDay.getMonth() + 1; //获取月份
      var fd = firstDay.getDate();
      firstDay = fy + "-" + fm + "-" + fd;
    // 如果不是周一
    } else {
      firstDay.setDate(firstDay.getDate() - (week -1))
      var fy = firstDay.getFullYear();
      var fm = firstDay.getMonth() + 1; //获取月份
      var fd = firstDay.getDate();
      firstDay = fy + "-" + fm + "-" + fd;
    }
  } else {
    // 最后一天正好是1231
    lastDay = lastDay.getFullYear() + "-12-31"
    firstDay.setDate(firstDay.getDate() - 6)
    var fy = firstDay.getFullYear();
    var fm = firstDay.getMonth() + 1; //获取月份
    var fd = firstDay.getDate();
    firstDay = fy + "-" + fm + "-" + fd;
  }
  console.log(lastDay)
  console.log(firstDay)
}

getsevenWeekdate();

猜你喜欢

转载自blog.csdn.net/weixin_45685252/article/details/112246874