【问题标题】:How to split time range into Array of weeks?如何将时间范围拆分为周数组?
【发布时间】:2020-07-27 11:33:47
【问题描述】:

如何将给定的时间段划分为从该时间段开始开始的周列表?

例如,我有:

from: 2020-07-27T08:08:20.794Z,
to: 2020-09-24T08:08:20.794Z

星期必须是这样的:

27.07.2020 - 03.08.2020
04.08.2020 - 11.08.2020
12.08.2020 - 19.08.2020
20.08.2020 - 27.08.2020
28.08.2020 - 04.09.2020
05.09.2020 - 12.09.2020
13.09.2020 - 20.09.2020
21.09.2020 - 24.09.2020

我尝试使用此代码:

function getWeeksInMonth(month, year){
   var weeks=[],
       firstDate=new Date(year, month, 1),
       lastDate=new Date(year, month+1, 0), 
       numDays= lastDate.getDate();
   
   var start=1;
   var end=7-firstDate.getDay();
   while(start<=numDays){
       weeks.push({start:start,end:end});
       start = end + 1;
       end = end + 7;
       if(end>numDays)
           end=numDays;    
   }        
    return weeks;
}  

但它只返回我提供的monthyear

【问题讨论】:

标签: javascript typescript datetime time


【解决方案1】:

您可以使用循环将日期增加 7 天,直到没有剩余天数为止。

const from = new Date("2020-07-27T08:08:20.794Z");
const to = new Date("2020-09-24T08:08:20.794Z");

// Convert date string to dd/mm/yyyy format
const buildDateString = (date) => {
  const day = date.getDate().toString().padStart(2, "0");
  const month = (date.getMonth() + 1).toString().padStart(2, "0");
  const year = date.getFullYear();
  
  return `${day}.${month}.${year}`;
}

// Increase date by x amount of days
const increaseDays = (date, amount) => new Date(date.setDate(date.getDate() + amount));

// Get all weeks in given period
const buildWeeks = (start, end) => {
  const weeks = [];
  let current = new Date(start);
  
  while(current < end) {
    // Get start of the week
    const beginOfWeek = new Date(current);
    // Get end of the week
    let endOfWeek = increaseDays(current, 6);
    // If there are less then 7 days left before the end, use the end.
    endOfWeek = endOfWeek > end ? end : endOfWeek;
    
    // Add week to our collection
    weeks.push([buildDateString(beginOfWeek), buildDateString(endOfWeek)]);
    
    current = increaseDays(current, 1);
  }
  
  return weeks;
}

const weeks = buildWeeks(from, to);

weeks.forEach(([start, end]) => console.log(`${start} - ${end}`));

没有 cmets

const from = new Date("2020-07-27T08:08:20.794Z");
const to = new Date("2020-09-24T08:08:20.794Z");

const buildDateString = (date) => {
  const day = date.getDate().toString().padStart(2, "0");
  const month = (date.getMonth() + 1).toString().padStart(2, "0");
  const year = date.getFullYear();
  
  return `${day}.${month}.${year}`;
}

const increaseDays = (date, amount) => new Date(date.setDate(date.getDate() + amount));

const buildWeeks = (start, end) => {
  const weeks = [];
  let current = new Date(start);
  
  while(current < end) {
    const beginOfWeek = new Date(current);
    let endOfWeek = increaseDays(current, 6);
    endOfWeek = endOfWeek > end ? end : endOfWeek;
    
    weeks.push([buildDateString(beginOfWeek), buildDateString(endOfWeek)]);
    current = increaseDays(current, 1);
  }
  
  return weeks;
}

const weeks = buildWeeks(from, to);
weeks.forEach(([start, end]) => console.log(`${start} - ${end}`));

Typescript 变体

const from = new Date("2020-07-27T08:08:20.794Z");
const to = new Date("2020-09-24T08:08:20.794Z");

const buildDateString = (date: Date) => {
  const day = date.getDate().toString().padStart(2, "0");
  const month = (date.getMonth() + 1).toString().padStart(2, "0");
  const year = date.getFullYear();
  
  return `${day}.${month}.${year}`;
}

const increaseDays = (date: Date, amount: number) => new Date(date.setDate(date.getDate() + amount));

const buildWeeks = (start: Date, end: Date) => {
  const weeks = [];
  let current = new Date(start);
  
  while(current < end) {
    const beginOfWeek = new Date(current);
    let endOfWeek = increaseDays(current, 6);
    endOfWeek = endOfWeek > end ? end : endOfWeek;
    
    weeks.push([buildDateString(beginOfWeek), buildDateString(endOfWeek)]);
    current = increaseDays(current, 1);
  }
  
  return weeks;
}

const weeks = buildWeeks(from, to);
weeks.forEach(([start, end]) => console.log(`${start} - ${end}`));

【讨论】:

  • 4.8.2020 是星期二
  • @mplungjan 不错!我在关注他的输出,把那几个星期是 8 天。现在全部修复
  • 你能告诉我为什么在 ts,const increaseDays = (date, amount) =&gt; new Date(date.setDate(date.getDate() + amount)); 给我返回错误:date.getDate is not a function
  • @nowymailhaha 我不知道,它应该可以工作,因为date 是日期类型。因此,只要您将其描述为const increaseDays = (date: Date, amount: number),它就可以工作。
  • 在TS中你必须添加let endDate = new Date(end);
【解决方案2】:

从一个日期到另一个日期,从星期一之后开始和/或在星期日之前结束时,周数不完整

const pad = num => ("0" + num).slice(-2);
const testDays = "sun,mo,tu,we,thu,fri,sat".split(",")
const makeDate = d => `${pad(d.getDate())}.${pad(d.getMonth()+1)}.${d.getFullYear()}`;

let from = new Date("2020-07-29T08:08:20.794Z");
const to = new Date("2020-09-23T08:08:20.794Z");
const aDay = 24 * 60 * 60 * 1000;
const aWeek = 7 * aDay;
const weeks = [];
const testArr = []
for (let i = from.getTime(), n = to.getTime(); i <= n; i += aDay) {
  const d = new Date(i);
  if (d.getDay() === 1 || weeks.length === 0) { // from OR monday
    weeks.push([makeDate(d)]);
    testArr.push([testDays[d.getDay()]])
  }
  else if (d.getDay()===0 || i===n) {
    weeks[weeks.length-1].push(makeDate(d))
    testArr[testArr.length-1].push(testDays[d.getDay()])
  }  
}
weeks.forEach((week,i) => console.log(`${week[0]} - ${week[1]}`,testArr[i].join("-")))

这个版本只会增加一周,不管是从

Monday to Sunday or
Sunday to Saturday 
Saturday to Friday
Friday to Thursday
Thursday to Wednesday
Wednesday to Tuesday
Tuesday to Monday

const pad = num => ("0" + num).slice(-2);
const testDays = "sun,mo,tu,we,thu,fri,sat".split(",")
const makeDate = d => `${pad(d.getDate())}.${pad(d.getMonth()+1)}.${d.getFullYear()}`;

let from = new Date("2020-07-29T08:08:20.794Z");
const to = new Date("2020-09-23T08:08:20.794Z");
const aDay = 24 * 60 * 60 * 1000;
const aWeek = 7 * aDay;
const weeks = [];
const testArr = []
for (let i = from.getTime(), n = to.getTime(); i <= n; i += aWeek) {
  const d1 = makeDate(new Date(i))
  let d2 = i+aWeek-aDay;
  if (d2 > n) d2 = n;
  d2 = makeDate(new Date(d2))
  weeks.push([d1,d2]);
  
}

weeks.forEach((week,i) => console.log(`${week[0]} - ${week[1]}`))

【讨论】:

  • 好的,但是当我将from 日期更改为例如29.07 时,我的数组从'03.08.2020', '09.08.2020' 周开始,而不是29.07.2020 - ...
  • 它不能只在星期一开始:/
  • 我已更新为从您的通票日期当天或之前的星期一开始
  • 星期必须从from日期开始,所以,如果我有from=29.07.2020,星期必须是29.07.2020-4.08.2020
  • 29.07.2020 - 02.08.2020 而不是29.07.2020 - 04.08.2020,在下一个相同的问题中
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-10-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-12
相关资源
最近更新 更多