JacobSiegel JacobSiegel - 1 year ago 68
Swift Question

(Swift) Setting UIDatePicker View from User Input

First I display a UIDatePicker on the screen and allow the user to choose a date and time. I save that value like this, which gets a date format that looks like this: 6/1/16, 1:47 PM

let time = NSDateFormatter.localizedStringFromDate(datePicker.date, dateStyle: .ShortStyle, timeStyle: .ShortStyle)

Later on in the application, I want users to be able to edit their original date, so when a button is pressed, I would like the UIDatePicker to display the time that they had originally chosen.

I am using the following code to try to make that happen, although the app keeps getting a runtime error because the date is always nil.

let dateFromatter = NSDateFormatter()
let date = dateFromatter.dateFromString("6/1/16, 1:47 PM")
datePicker.setDate(date!, animated: true)

Thank you for your help!

Answer Source

You are having an issue with the date format and not with the date picker.

 @IBOutlet weak var datePicker: UIDatePicker!
 override func viewDidLoad() {

    let dateFromatter = NSDateFormatter()
    dateFromatter.dateFormat = "M/d/yy, H:mm"
    if let date = dateFromatter.dateFromString("6/1/16, 1:47") {
      datePicker.setDate(date, animated: true)