How to check if 24 hours have passed in Swift

You can use UserDefault to save the date upon creation of the record. The syntax will be

UserDefaults.standard.set(Date(), forKey:"creationTime")

Whenever you want to check the saved date, retrieve it in this way

if let date = UserDefaults.standard.object(forKey: "creationTime") as? Date {
    if let diff = Calendar.current.dateComponents([.hour], from: date, to: Date()).hour, diff > 24 {
        //do something
    }
}

You can easily check if the time interval since date is greater or equal to a TTL of 24 hours.

let start = Date()
let timeToLive: TimeInterval = 60 * 60 * 24 // 60 seconds * 60 minutes * 24 hours

let isExpired = Date().timeIntervalSince(start) >= timeToLive

Tags:

Nsdate

Swift3