How to compare dates in Swift

Dec 18, 2021 1 min read
How to compare dates in Swift

Let's say you want to track x event the user do at x time/date, for instance track when certain api was updated. For that you create a variable:

// Stores the last time the API was updated, it will be updated once a week
    @AppStorage("coingekoWhiteListApiLastUpdated") var coingekoWhiteListApiLastUpdated: Date = Date()

Now on your function you can check like this:

let isSameWeek = coingekoWhiteListApiLastUpdated.isInThisWeek

// If the weeks are different then update API
if(!isSameWeek) {
    await updateCoingekoApi()
}

The function to check this would look like this:

// Checks if Dates are the same or different
extension Date {
    func isEqual(to date: Date, toGranularity component: Calendar.Component, in calendar: Calendar = .current) -> Bool {
        calendar.isDate(self, equalTo: date, toGranularity: component)
    }

    func isInSameYear(as date: Date) -> Bool { isEqual(to: date, toGranularity: .year) }
    func isInSameMonth(as date: Date) -> Bool { isEqual(to: date, toGranularity: .month) }
    func isInSameWeek(as date: Date) -> Bool { isEqual(to: date, toGranularity: .weekOfYear) }

    func isInSameDay(as date: Date) -> Bool { Calendar.current.isDate(self, inSameDayAs: date) }

    var isInThisYear:  Bool { isInSameYear(as: Date()) }
    var isInThisMonth: Bool { isInSameMonth(as: Date()) }
    var isInThisWeek:  Bool { isInSameWeek(as: Date()) }

    var isInYesterday: Bool { Calendar.current.isDateInYesterday(self) }
    var isInToday:     Bool { Calendar.current.isDateInToday(self) }
    var isInTomorrow:  Bool { Calendar.current.isDateInTomorrow(self) }

    var isInTheFuture: Bool { self > Date() }
    var isInThePast:   Bool { self < Date() }
}

You can also do some common operations such as:

let now = Date()
let soon = Date().addingTimeInterval(5000)

now == soon
now != soon
now < soon
now > soon

Note: addingTimeInterval is in Seconds.

Great! Next, complete checkout for full access to ArturoFM.
Welcome back! You've successfully signed in.
You've successfully subscribed to ArturoFM.
Success! Your account is fully activated, you now have access to all content.
Success! Your billing info has been updated.
Your billing was not updated.