如何使用时刻获取最近3周的日期范围?

时间:2018-08-31 05:27:40

标签: javascript date momentjs

我需要最近3周的日期范围,包括当前星期的日期范围。

例如:今天的日期是:2018年8月31日

输出将是:

Aug 26 - Sep 01 , Aug 19 - Aug 25 , Aug 12 - Aug 18

3 个答案:

答案 0 :(得分:2)

您可以使用.startOf('week')查找一周的开始。

var currentWeek = getWeekRange(0);
var lastWeek = getWeekRange(-1);
var weekBeforeLast = getWeekRange(-2);

var currentWeek2 = getWeekRange2(0);

console.log(currentWeek, lastWeek, weekBeforeLast, currentWeek2);

function getWeekRange(week = 0) {
  var weekStart = moment().add(week, 'weeks').startOf('week');
  
  return [...Array(7)].map((_, i) => 
    weekStart.clone().add(i, 'day').format('DD/MM/YYYY')
  );
}

function getWeekRange2(week = 0) {
 var weekStart = moment().add(week, 'weeks').startOf('week');
 var days = [];
 for (var i = 0; i < 7; i++) {
   days.push(weekStart.clone().add(i, 'day').format('DD/MM/YYYY'));
 }
 return days;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.js"></script>


为澄清起见:

[...Array(7)]是为了简洁起见。它正在创建一个包含7个Array项目(即undefined)的[undefined, undefined, ...]。这些项目被视为占位符,并将使用.map()映射到一周中的几天。

尽管是undefined,但我使用数组中的项目index来增加星期几-换句话说,数组的第一项[undefined]将的index0,因此我们将添加0天,并添加到一周结束。

您还可以执行以下操作:

function getWeekRange(week = 0) {
  var weekStart = moment().add(week, 'weeks').startOf('week');
  var days = [];
  for (var i = 0; i < 7; i++) {
    days.push(weekStart.clone().add(i, 'day').format('DD/MM/YYYY'));
  }
  return days;
}

答案 1 :(得分:0)

尝试一下

moment().range(moment().subtract(3, 'weeks'), moment());

moment().subtract(3, 'weeks') this line will return the time before 3 weeks, moment() will return time now and range() will take the range from those two.

希望它会有所帮助:)

答案 2 :(得分:0)

 let startOfWeek = moment().subtract(1, 'weeks').startOf('week').toDate().toISOString();
 let endOfWeek = moment().subtract(1, 'weeks').endOf('week').toDate().toISOString();
 console.log(startOfWeek, endOfWeek)