Search code examples
iosswiftuidatepicker

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


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


Solution

  • 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)