Swift version: 5.2
Calendar object gives us lots of useful methods for evaluating dates in various ways. One of the most useful is the method
isDate(_:equalTo:toGranularity:), which lets us compare two dates at a specific level of granularity: do these two dates occur in the same minute? The same hour? Or day, week, year?
As an example, here are two dates for us to work with:
let first = Date() let second = Date().addingTimeInterval(10000)
We can now check whether those two occur within the same day, like this:
let sameDay = Calendar.current.isDate(first, equalTo: second, toGranularity: .day)
If all you want to do is check whether a date points to some time during today, you should use
let isToday = Calendar.current.isDateInToday(first)
SPONSORED Catch bugs as soon as they happen and know exactly why a crash occurred. Instabug's SDK grabs all the logs they need to fix bugs, crashes and performance issues in minutes instead of days. Get screenshots, device details, network logs, repro steps, and tons of other critical insights needed to resolve issues and prioritize product backlogs straight from your dashboard. It only takes a minute to integrate!
Available from iOS 8.0
This is part of the Swift Knowledge Base, a free, searchable collection of solutions for common iOS questions.
Link copied to your pasteboard.