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

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

程序员文章站 2022-06-07 11:49:20
...
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();
相关标签: javascript