例如,用户选择01/2020到01/2020的月份范围来过滤上载的报告,而他的报告日期范围是06/01/2020到13/01/2020。这不符合要求,因为它缺少完成该月的日期范围(从01/01/2020到06/01/2020以及从13/01/2020到31/01/2020)。因此,我需要找到该月的缺失日期范围,并要求用户上传该时间段的报告。我已经尝试通过查找给定月份(01/2020-01/2020)(filterDateArray)中所有天的数组与报告具有的天的数组(06/01/2020-13)的差来获取缺少日期的数组/ 01/2020)(existingDateArray):
filterDateArray.filter(x => !existingDateArray.includes(x))
这将返回月份中所有缺少的日期的数组
[
'01/01/2020', '02/01/2020',
'03/01/2020', '04/01/2020',
'05/01/2020', '14/01/2020',
'15/01/2020', '16/01/2020',
'17/01/2020', '18/01/2020',
'19/01/2020', '20/01/2020',
'21/01/2020', '22/01/2020',
'23/01/2020', '24/01/2020',
'25/01/2020', '26/01/2020',
'27/01/2020', '28/01/2020',
'29/01/2020', '30/01/2020',
'31/01/2020'
]
问题是,我无法为该数组中的缺失报告获取日期范围。预期结果的日期范围应为01/01/2020至06/01/2020和13/01/2020至31/01/2020。这意味着用户应至少再上传两个报告才能完成月份
在我看来,缺少的范围是:
您可以创建一个函数来根据日期数组创建范围,该日期范围从第一个日期的第一个范围开始和结束。然后,它检查每个后续日期是否是第二天。如果不是,则前一个日期是该范围的最后一天,当前日期是下一个范围的第一天,依此类推。当到达数组末尾时,它将关闭当前范围(如果有)。
例如修改后的数据以包括单日范围:
// parse d/m/y to Date
function datesToRanges(dates) {
let parse = s => {
let [d, m, y] = s.split(/\D/);
return new Date(y, m-1, d);
}
// Add 1 day to a date, return the date
let add = d => {
d.setDate(d.getDate() + 1);
return d;
}
// Pad single digit numbers with leading zero
let z = n => (n<10?'0':'') + n;
// Format Date as d/m/y
let format = d => `${z(d.getDate())}/${z(d.getMonth()+1)}/${d.getFullYear()}`;
// Initialise variables
let startRange, endRange, endPlusOne, ranges = [];
// Loop over dates
for (let i=0, iLen=dates.length; i < iLen; i++) {
// Initialise start and end range if not set
if (!startRange) {
startRange = dates[i];
endRange = startRange;
i++;
}
// Get a string for endRange + 1 day
endPlusOne = format(add(parse(endRange)));
// If current == next date and there are more dates
// to come, update endRange
if (endPlusOne == dates[i] && dates[i+1]) {
endRange = endPlusOne;
// Otherwise, at end of current range
// Write range to result, update start and end
// If at end of array, write last range
} else {
ranges.push(startRange + ' - ' + endRange);
startRange = dates[i];
endRange = startRange;
// Check if at end of dates array and have started a range
if (!dates[i+1] && startRange) {
ranges.push(startRange + ' - ' + endRange);
}
}
}
return ranges;
}
// data
let dates = ['01/01/2020', // Single date at start
'03/01/2020','04/01/2020','05/01/2020', // 3 day range
'14/01/2020','15/01/2020','16/01/2020', // 7 day range
'17/01/2020','18/01/2020','19/01/2020',
'20/01/2020',
'22/01/2020', // Single date range
'24/01/2020','25/01/2020','26/01/2020', // 6 day range
'27/01/2020','28/01/2020','29/01/2020',
'31/01/2020']; // Single date at end
console.log(datesToRanges(dates).join('\n'));