How to change UIDatePicker to a specific time (in code)

ilan picture ilan · Mar 11, 2015 · Viewed 21.1k times · Source

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

Answer

arthankamal picture arthankamal · Mar 11, 2015

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)