Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if 24 hours have passed in Swift

Tags:

swift3

nsdate

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.

like image 213
Tom Derry Marion Mantilla Avatar asked Jul 12 '17 01:07

Tom Derry Marion Mantilla


People also ask

How can I check if a date is valid in Swift?

Use DateFormatter class... It can be used to check any string whether it is a valid date or not and accordingly the string can be converted into nsdata.

How do I get the difference between two timestamps in Swift?

Date Difference Extension in Swiftlet formatter = DateFormatter() formatter. dateFormat = "yyyy/MM/dd HH:mm" let xmas = formatter. date(from: "2021/12/24 00:00") let newYear = formatter. date(from: "2022/01/01 00:00") print(newYear!


2 Answers

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
    }
}
like image 125
Fangming Avatar answered Oct 11 '22 12:10

Fangming


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
like image 31
Mycroft Canner Avatar answered Oct 11 '22 14:10

Mycroft Canner