How to check if two date ranges overlap in Swift

Published on: January 17, 2020

Dates in Swift can be compared to each other. This allows you to check whether one date comes before or after another date:

if dateOne > dateTwo {
  print("dateOne comes after dateTwo")
} else if dateOne < dateTwo {
  print("dateOne comes before dateTwo")
} else if dateOne == dateTwo {
  print("dateOne is equal to dateTwo")
}

You can also use dates in Swift to create ranges. And when you have one range, you can check whether it overlaps with another date. Let's look at an example:

struct Meeting {
  let startDate: Date
  let endDate: Date
}

func doMeetingsOverlap(_ meetingOne: Meeting, _ meetingTwo: Meeting) -> Bool {
  let leftRange = meetingOne.startDate ... meetingOne.endDate
  let rightRange = meetingTwo.startDate ... meetingTwo.endDate

  return leftRange.overlaps(rightRange)
}

In this sample code, we create a closed range using an object's start and end dates. This is done for two objects that we wanted to compare, and we then use ClosedRange's overlaps(_:) method to check if one date range has overlap with the other date range. Nice and simple!

If you have any questions about this tip, or if you have feedback for me, make sure to send me a Tweet.

Categories

Swift Tips

Subscribe to my newsletter