我想從日期陣列中獲取所有日期范圍。
例如:
getDates([
2022-01-01,
2022-01-02,
2022-01-03,
2022-01-04,
2022-01-09,
2022-01-10,
2022-01-15
])
會回來
[
{start: 2022-01-01, end: 2022-01-04},
{start: 2022-01-09, end: 2022-01-10},
{start: 2022-01-15, end: 2022-01-15}
]
uj5u.com熱心網友回復:
- 使用
Array#sort, 對日期陣列進行排序 - 使用
Array#reduce,在更新范圍串列時迭代排序串列。- 在每次迭代中,檢查當前日期和當前范圍結束之間的天數差。如果大于一個,則推送一個新的范圍,否則,將當前范圍的末尾更新為當前日期
const _getDifferenceInDays = (date1, date2) => {
const difference = date2.getTime() - date1.getTime();
return difference / (1000 * 3600 * 24);
}
const getDates = (dates = []) => {
const arr = [...dates].sort((a, b) => new Date(a) - new Date(b));
const ranges = arr.reduce((ranges, current) => {
if(ranges.length === 0) { // first-iteration
ranges.push({ start: current, end: current });
}
const currentRange = ranges[ranges.length - 1];
const endDate = new Date(currentRange.end);
const currentDate = new Date(current);
if(_getDifferenceInDays(endDate, currentDate) > 1) {
ranges.push({ start: current, end: current });
} else {
currentRange.end = current;
}
return ranges;
}, []);
return ranges;
}
console.log( getDates(['2022-01-01', '2022-01-02', '2022-01-03', '2022-01-04', '2022-01-09', '2022-01-10', '2022-01-15']) );
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/524896.html
標籤:javascript日期
