How to store date in userdefaults?

The following saves a Date object as a Double (a.k.a. TimeInterval). This avoids any date formatting. Formatting can lose precision, and is unnecessary since the string is not intended for users to read.

// save
UserDefaults.standard.set(Date().timeIntervalSince1970, forKey: key)

// read
let date = Date(timeIntervalSince1970: UserDefaults.standard.double(forKey: key))

If you only want to display the date value you can convert and store it as string otherwise you convert/format it after you have read it, either way you should make sure you use the same type when saving and reading

//save as Date
UserDefaults.standard.set(Date(), forKey: key)

//read
let date = UserDefaults.standard.object(forKey: key) as! Date
let df = DateFormatter()
df.dateFormat = "dd/MM/yyyy HH:mm"
print(df.string(from: date))

// save as String
let df = DateFormatter()
df.dateFormat = "dd/MM/yyyy HH:mm"
let str = df.string(from: Date())
UserDefaults.standard.setValue(str, forKey: key)

// read
if let strOut = UserDefaults.standard.string(forKey: key) {
    print(strOut)
}

Tags:

Date

Swift