0

I have saved a date using UserDefaults and my values are being saved and I trying to present my saved date as a string in my view controller but it comes up blank. Am I implementing it wrong?

@IBOutlet weak var timeLabel: UILabel!

let formatter = DateFormatter()

func savedate(){

    UserDefaults.standard.set(datePicker.date, forKey: keyDate)

}

func loadDate(animation: Bool) {

    guard let loadedDate = UserDefaults.standard.object(forKey: keyDate) as? Date else { return }

    datePicker.setDate(loadedDate, animated: true)

    print(loadedDate)

    let loadedValue = formatter.string(from: loadedDate)
    timeLabel.text = loadedValue
}

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(true)
    loadDate(animation: true)
 }
@IBAction func saveTimeValue(_ sender: Any) {
saveDate()
}
Hightower98
  • 245
  • 3
  • 14

1 Answers1

1

Your problem is that you didn't set your date formatter options. As it is it will return an empty string for any date:

Try

let formatter = DateFormatter()
formatter.string(from: Date())  // ""

To format your date properly using a localized description you can take a look at this answer.

Leo Dabus
  • 229,809
  • 59
  • 489
  • 571