Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store date in userdefaults?

Tags:

I'd like to record the history of her entry into the textfield. I intend to register this with UserDefaults. But when I try to save it with UserDefaults, "cannot assign value of type 'nsdate'?'to type 'String' " Error. I don't think it's accepting textfield data because it's string. And how can I keep history in memory?

formatteddate and formatteddate2 give this error. The date output is as follows : 20/04/2019 20:23

let token = try? keychain.getString("chipnumbernew")
        chip1InfoString = token

        var time = NSDate()
        var formatter = DateFormatter()
        formatter.dateFormat = "dd/MM/yyyy HH:mm"
        var formatteddate = formatter.string(from: time as Date)
        var formatteddate2 = formatter.string(from: time as Date)

        timertextNew.text = formatteddate
        timertext2New.text = formatteddate2


        let RetrivedDate = UserDefaults.standard.object(forKey: "timertext") as? NSDate

       formatteddate = RetrivedDate

        let RetrivedDate2 = UserDefaults.standard.object(forKey: "timertext2") as? NSDate
        formatteddate2 = RetrivedDate2
like image 822
stakabekor Avatar asked Apr 20 '19 17:04

stakabekor


1 Answers

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)
}
like image 159
Joakim Danielson Avatar answered Nov 02 '22 22:11

Joakim Danielson