Better comparing Dates in Swift using Calendar (iOS/macOS)

Thorsten Stark
2 min readMar 10, 2019
Photo by Eric Rothermel on Unsplash

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 Calendarwhich 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

In case you only want to check if a given date is on the same day as an other date, Calendar has some more funtions to offer. The most general of them is isDate(_ date1: Date, inSameDayAs date2: Date) -> Bool . The others are:

func isDateInToday(_ date: Date) -> Boolfunc isDateInTomorrow(_ date: Date) -> Boolfunc isDateInYesterday(_ date: Date) -> Boolfunc isDateInWeekend(_ date: Date) -> Bool

--

--

Thorsten Stark

Senior iOS Developer @TBOagency – Swift, Objc, UI&UX, CI/CD