How to change UIDatePicker to a specific time (in code)
Swift 3 and 4:
extension UIDatePicker {
func setDate(from string: String, format: String, animated: Bool = true) {
let formater = DateFormatter()
formater.dateFormat = format
let date = formater.date(from: string) ?? Date()
setDate(date, animated: animated)
}
}
Usage:
datePicker.setDate(from: "1/1/2000 10:10:00", format: "dd/MM/yyyy HH:mm:ss")
You've to change the time, you can do it using NSDateComponents
and set the modified date to your DatePicker
var calendar:NSCalendar = NSCalendar.currentCalendar()
let components = calendar.components(NSCalendarUnit.HourCalendarUnit | NSCalendarUnit.MinuteCalendarUnit, fromDate: NSDate())
components.hour = 5
components.minute = 50
datePicker.setDate(calendar.dateFromComponents(components)!, animated: true)