将日期范围划分为相等的块,其中包含一定数量的JavaScript中的天块? [英] Dividing a date range into equal chunks containing a set number of day chunks in JavaScript?
问题描述
我正在尝试编写一个函数,但我试图画出一个空白,试图把头缠在如何实现目标上.
I am trying to write a function but I'm drawing a blank trying to wrap my head around how to achieve my goal.
我正在为API编写包装程序,该包装程序可以按开始日期和结束日期过滤数据,但一次只能请求90天的数据,而不能对数据进行分页.
I am writing a wrapper for an API that filters data by a start date and an end date but will only let you request 90 days of data at a time and does not paginate data.
我想编写一个函数,该函数接受 startDate
, endDate
和 maxDays
,然后将日期范围拆分为较小的相等开始和结束块,其长度不超过 maxDays
约束.
I would like to write a function that would take in a startDate
, endDate
and maxDays
that would then split the date range down into smaller equal start and end chunks containing no more than the maxDays
constraint.
这些块不应彼此重叠,但应保留原始的 startDate
和 endDate
.
The chunks should not overlap each-other but the original startDate
and endDate
should be preserved.
函数应返回对象数组.例如:
The function should return an array of objects. For example:
[
{ start: "", end: "" },
{ start: "", end: "" },
...
]
推荐答案
从开始日期开始,并添加 maxDays 以获取代码块的结尾.如果阻止日期大于结束日期,请改用结束日期.然后将 maxDays 添加到开始位置,然后再次运行,直到开始位置比结束位置> =
为止.
Start with the start date and add maxDays to get the end of the block. If the block date is greater than the end date, use the end date instead. Then add maxDays to the start and go again until the start is >=
than the end.
在将数据推送到数组之前复制日期,以免影响原始或正在进行的处理.
Copy dates before pushing into the array so don't affect original or ongoing processing.
function getDateBlocks(start, end, maxDays) {
let result = [];
// Copy start so don't affect original
let s = new Date(start);
while (s < end) {
// Create a new date for the block end that is s + maxDays
let e = new Date(s.getFullYear(), s.getMonth(), s.getDate() + maxDays);
// Push into an array. If block end is beyond end date, use a copy of end date
result.push({start:new Date(s), end: e <= end? e : new Date(end)});
// Increment s to the start of the next block which is one day after
// the current block end
s.setDate(s.getDate() + maxDays + 1);
}
return result;
}
console.log(getDateBlocks(new Date(2021,0,1), new Date(2021,0,20), 6));
您需要确定日期是否包含在内.在上面的代码中,6天的时间段将是1月1日至7日,1月8日至14日,依此类推.如果您希望1至6日,7至13日等,请在 maxDays 中减去1,然后再执行 while 循环.
You need to work out if the dates are inclusive or not. In the above, 6 day blocks will go 1–7 Jan, 8–14 Jan, etc. If you want 1–6, 7–13, etc. subtract 1 from maxDays before doing the while loop.
您还应该检查 maxDays 是一个正整数,否则循环可能是无限的……
You should also check that maxDays is a positive integer or the loop may be be infinite…
这篇关于将日期范围划分为相等的块,其中包含一定数量的JavaScript中的天块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!