(Swift) Setting UIDatePicker View from User Input

2019-09-12 00:21发布

问题:

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!

回答1:

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

 @IBOutlet weak var datePicker: UIDatePicker!
 override func viewDidLoad() {
    super.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)
    }
  }


回答2:

For a short style string use below format:

let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "M/d/yy, H:mm"
dateFormatter.stringFromDate(NSDate())