效果:
//日期合并
mergeDates(dates) {
// 将日期列表按照从小到大的顺序排序
dates.sort(function (a, b) {
return a - b;
});
console.log("sort", dates)
let start = 0;
let end = 0;
const mergedDates = [];
for (let i = 1; i < dates.length; i++) {
let diff = (new Date(dates[i]).getTime() - new Date(dates[i - 1]).getTime()) / (1000 * 60 * 60 * 24)
if (diff == 1) { // 判断相邻日期是否连续
end = i;
} else {
if (end - start + 1 >= 3) { // 判断当前日期段是否满足合并条件
let startTime1 = formatting(new Date(dates[start]).getTime()).day
let endTime1 = formatting(new Date(dates[end]).getTime()).day
// mergedDates.push(`${dates[start]}~${dates[end]}`);
mergedDates.push(`${startTime1}日~${endTime1}日`);
} else {
for (let j = start; j <= end; j++) {
let oneTime1 = formatting(new Date(dates[j]).getTime()).day
// mergedDates.push(dates[j]);
mergedDates.push(oneTime1 + '日');
}
}
start = i;
end = i;
}
}
if (end - start + 1 >= 3) { // 处理最后一段日期
let startTime2 = formatting(new Date(dates[start]).getTime()).day
let endTime2 = formatting(new Date(dates[end]).getTime()).day
// mergedDates.push(`${dates[start]}~${dates[end]}`);
mergedDates.push(`${startTime2}日~${endTime2}日`);
} else {
for (let j = start; j <= end; j++) {
let oneTime2 = formatting(new Date(dates[j]).getTime()).day
// mergedDates.push(dates[j]);
mergedDates.push(oneTime2 + '日');
}
}
console.log("mergedDates", mergedDates)
return mergedDates;
},
dates格式:
const dates = [
new Date('2021-01-01'),
new Date('2021-01-02'),
new Date('2021-01-03'),
new Date('2021-01-05'),
new Date('2021-01-06'),
]
time.js:
//处理时间
export function formatting(time) {
var time = new Date(time);
var y = time.getFullYear();
var m = time.getMonth() + 1;
var d = time.getDate();
var h = time.getHours();
var mm = time.getMinutes();
var s = time.getSeconds();
m = m<10?"0"+m:m
d = d<10?"0"+d:d
h = h<10?"0"+h:h
mm = mm<10?"0"+mm:mm
s = s<10?"0"+s:s
let obj = {
date: y + "-" + m + "-" + d + " ",
time: h + ":" + mm + ":" +s,
day: d
};
return obj;
};
参考:
不过是连续两个以上就合并了
Java后台如何判断一串数字是否连续,连续合并数字