Better comparing Dates in Swift using Calendar

Better comparing Dates in Swift using Calendar

We often come in a situation where we have to check whether a given Date is on a specific day, hour or week or something like that. In the past we solved this by calculating the date with 0 hours and 0 minutes and then compare it with our given Date. This approach becomes even more complicated and error-prone when you have to work with different timezones.

Fortunately there is a struct called Calendar which has the pretty little method func compare(_ date1: Date, to date2: Date, toGranularity component: Calendar.Component) -> ComparisonResult. As its name suggest, it compares two Date objects to a given granularity

var calender = Calendar.current
calender.timeZone = TimeZone.current
let result = calender.compare(date, to: now, toGranularity: .day)
let isSameDay = result == .orderedSame

Instead of .day also every other Calendar.Component is possible. Here is a list of some (but not all) Calendar.Component :

  • .minute
  • .second
  • .month
  • .weekOfMonth
  • .weekday