Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 754
ilan Avatar asked Mar 11 '15 11:03

ilan


4 Answers

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")
like image 45
zombie Avatar answered Nov 05 '22 10:11

zombie


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)
like image 101
arthankamal Avatar answered Nov 05 '22 10:11

arthankamal


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)
like image 5
Kevin Horgan Avatar answered Nov 05 '22 09:11

Kevin Horgan


Swift 5

let calendar = Calendar.current
var components = DateComponents()
components.hour = 5
components.minute = 50
    
timePicker.setDate(calendar.date(from: components)!, animated: false)
like image 5
Jay Mutzafi Avatar answered Nov 05 '22 11:11

Jay Mutzafi