Error in DataPicker Format

48 Views Asked by At
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "HH:mm "

let selectedDate = dateFormatter.string(from: sender.date)

UserDefaults.standard.set(selectedDate, forKey: "date")
print(selectedDate)

\\method to reload the selected time inside the viewdidLoad func

let selectedDate = UserDefaults.standard.object(forKey: "date")
example.setDate(selectedDate as! Date ?? Date(), animated: false)

But when I run the application it returns this error

Could not cast value of type '__NSCFString' (0x108e8b4f0) to 'NSDate' (0x108e8c0d0).

I converted to HH: mm because I want to record only the time in this format, but I do not know how I'm going to handle it

2

There are 2 best solutions below

0
Dávid Pásztor On

You should be storing the Date object itself in UserDefaults and not its String representation. In most use cases, it makes more sense to store a Date object, since Date objects represent an absolute point in time and hence you can use them for date comparison or to convert them to local times.

Moreover, it looks like that the setDate function actually expects a Date object and not a String, hence it doesn't make sense to generate a String representation of a Date and then store that in UserDefaults.

//Save the Date object
UserDefaults.standard.set(sender.date, forKey: "date")

//Retrieve the Date object, if it cannot be retrieved, use the current Date
if let selectedDate = UserDefaults.standard.object(forKey: "date") as? Date {
    example.setDate(selectedDate, animated: false)
} else {
    example.setDate(Date(), animated: false)
}
2
Amir Khan On

Andre you save String value in UserDefaults and try to set NSDate from String. If you concern with the time only then my advice to save the date as it is in UserDefaults and get the time as formatted as per as your requirement.

Here are the following steps for saving and retrieving Time :

For saving:

   func datePickerChanged(_ sender: UIDatePicker){

    UserDefaults.standard.set(sender.date, forKey: "date")

}

For Retrieving:

 func getTime(){

    let date = UserDefaults.standard.object(forKey: "date") as! Date

    let dateFormatter = DateFormatter()
    dateFormatter.locale = NSLocale.current
    dateFormatter.timeZone = NSTimeZone(name: "UTC") as TimeZone! //Set your own time zone here.

    dateFormatter.dateFormat = "HH:mm"

    print(dateFormatter.string(from: date as Date))

    example.setDate(date, animated: false)

}

Hope it will help you and save your time.