How to set a specific default time for a date picker in Swift
Swift 5
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "HH:mm"
if let date = dateFormatter.date(from: "17:00") {
print(date) // 2000-01-01 22:00:00 +0000
datePicker.date = date
}
Additional note: If you've already set datePicker.minimumDate and you're using this dateFormat the date/time will default to it's earliest possible date--wasted an hour on this :|
Are you looking for setting the time through a string. If that''s the case you can use a date formatter like this.
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "HH:mm"
let date = dateFormatter.dateFromString("17:00")
datePicker.date = date
Adding an init to the Picker class
init(time:String) {
super.init(frame: CGRectMake(0, 0, UIScreen.mainScreen().bounds.size.width, UIScreen.mainScreen().bounds.size.height))
setupView()
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "HH:mm"
if let date = dateFormatter.dateFromString("17:00") {
datePicker.date = date
}
}
with swift 4+
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "HH:mm"
let date = dateFormatter.date(from: "17:00")
datePicker.date = date