analyze
First of all, there are two main scenarios for overlapping date segments:
- date_segment contains date_segment2 ;
- Date segment 2 contains date segment 1 .
The translation of the above is that
if the start date of date segment 2 is after the start date of date segment 1 , date segment 1 may include date segment 2 ;
if the start date of date segment 2 is before the start date of date segment 1 , then It is possible that date segment 2 contains date segment 1 .
Then we assume that the start date and end date of date segment 1 are A and B respectively, and the start date and end date of date segment 2 are X and Y respectively. Based on date segment 1 , first list the start date of date segment 1 <= In the case of the start date of date segment 2 .
日期段1 开始日 = 日期段2 开始日:
1. 日期段2 开始日 = 日期段1 开始日
A------B
XY
X--Y
X------Y
X----------Y
日期段1 开始日 < 日期段2 开始日:
2. 日期段1 开始日 < 日期段2 开始日 < 日期段1 结束日
A------B
XY
X--Y
X----Y
X-------Y
3. 日期段2 开始日 = 日期段1 结束日
A------B
XY
X---Y
3. 日期段2 开始日 > 日期段1 结束日
A------B
XY
X---Y
Next, based on date segment 1 , list the cases where the start date of date segment 1 > date segment 2 .
(It can also be changed to date segment 2 as the benchmark, and A, B, X, and Y in the above analysis can be exchanged)
日期段1 开始日 > 日期段2 开始日:
4. 日期段2 结束日 < 日期段1 开始日
X---Y
A------B
5. 日期段2 结束日 = 日期段1 开始日
X-----Y
A------B
6. 日期段1 开始日 > 日期段2 结束日 > 日期段1 结束日
X--------Y
A------B
7. 日期段2 结束日 = 日期段1 结束日
X------------Y
A------B
8. 日期段2 结束日 > 日期段1 结束日
X---------------Y
A------B
in conclusion
By observing the above analysis, it is found that the segment dates of only two scenarios do not coincide:
- Type 3: Start date of date range 1 < start date of date range 2 , and start date of date range 2 > end date of date range 1
- Type 4: start date of date range 1 > start date of date range 2 , and end date of date range 2 < start date of date range 1
Then, other situations outside these two scenarios are judged as duplication.
the code
function isDuplicateDatePeriod(currPeriod = [], otherPeriod = []) {
const [currStartDay, currEndDay] = currPeriod;
const [otherStartDay, otherEndDay] = otherPeriod;
if (!currStartDay || !currEndDay || !otherStartDay || !otherEndDay) {
// 日期不完整,认为不重复
return false;
}
const currStartTime = new Date(currStartDay).getTime();
const currEndTime = new Date(currEndDay).getTime();
const otherStartTime = new Date(otherStartDay).getTime();
const otherEndTime = new Date(otherEndDay).getTime();
if (otherStartTime > currStartTime) {
// 其他日期段开始日期大于当前日期段开始日日期,那么其他日期段开始日期小于等于当前日期段结束日则为重复
return otherStartTime <= currEndTime;
} else if (otherStartTime < currStartTime) {
// 其他日期段开始日期小于当前开始日期,那么其他日期段结束日期大于等于当前日期段开始日期则为重复
return otherEndTime >= currStartTime;
} else {
// 其他日期段开始日期=当前日期段开始日期,一定重复
return true
}
}