How to check if 24 hours have passed in Swift

2020-02-23 04:26发布

问题:

I have to implement in my app where after a user had saved his recording, I will have to determine if 24 hours have passed from the creation date of that recording. So far what I have at the moment is just to determine if current date is not equal to the creation date. I really appreciate anybody's help, thanks in advance.

回答1:

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


回答2:

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


标签: swift3 nsdate