I need to change the UIDatePicker to a specific dynamically.
My date picker is set to time mode only. i can set the time with
timePicker.setDate(NSDate(), animated: false)
but i cant figure out how to change it to a different time and not to current time.
So how do i change it?
Thanks
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)
To set the date pick (time only) to a specific time such as "09:00" I would set the NSDateComponents and picker like this.
let calendar = NSCalendar.currentCalendar()
let components = NSDateComponents()
components.hour = 9
components.minute = 0
timePicker.setDate(calendar.dateFromComponents(components)!, animated: true)
Swift 5
let calendar = Calendar.current
var components = DateComponents()
components.hour = 5
components.minute = 50
timePicker.setDate(calendar.date(from: components)!, animated: false)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With