Skip to content

Instantly share code, notes, and snippets.

@thanapongp
Created April 4, 2024 04:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thanapongp/261d94b94a4674d556ca7dd3ece5ab5d to your computer and use it in GitHub Desktop.
Save thanapongp/261d94b94a4674d556ca7dd3ece5ab5d to your computer and use it in GitHub Desktop.
Quick and easy dates ranges overlap check
export function isRangesOverlap(
firstRange: [Date, Date],
secondRange: [Date, Date]
): boolean {
const firstRangeStart = firstRange[0].getTime();
const secondRangeStart = secondRange[0].getTime();
const firstRangeEnd = firstRange[1].getTime();
const secondRangeEnd = secondRange[1].getTime();
const firstComparatorStart = firstRangeStart > secondRangeStart ? secondRangeStart : firstRangeStart;
const secondComparatorStart = firstRangeStart > secondRangeStart ? firstRangeStart : secondRangeStart;
const firstComparatorEnd = firstRangeEnd > secondRangeEnd ? secondRangeEnd : firstRangeEnd;
const secondComparatorEnd = firstRangeEnd > secondRangeEnd ? firstRangeEnd : secondRangeEnd;
// 10...20
// 12...24
// 10 < 12 && 24 > 20
if (firstComparatorStart < secondComparatorStart && secondComparatorEnd > firstComparatorEnd) {
return true;
}
// 10...15
// 12...13
// 10 < 12 && 13 < 15
if (firstComparatorStart < secondComparatorStart && secondComparatorEnd < firstComparatorEnd) {
return true;
}
// 10...15
// 09...11
// 10 > 09 && 11 < 15
if (firstComparatorStart > secondComparatorStart && secondComparatorEnd < firstComparatorEnd) {
return true;
}
return false;
}
console.log(
isRangesOverlap(
[new Date(2024, 3, 12), new Date(2024, 3, 24)],
[new Date(2024, 3, 10), new Date(2024, 3, 20)],
)
)
console.log(
isRangesOverlap(
[new Date(2024, 3, 12), new Date(2024, 3, 13)],
[new Date(2024, 3, 10), new Date(2024, 3, 15)],
)
)
console.log(
isRangesOverlap(
[new Date(2024, 3, 9), new Date(2024, 3, 11)],
[new Date(2024, 3, 10), new Date(2024, 3, 15)],
)
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment