Reputation: 4462
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
Upvotes: 18
Views: 27236
Reputation: 161
Swift 5
let calendar = Calendar.current
var components = DateComponents()
components.hour = 5
components.minute = 50
timePicker.setDate(calendar.date(from: components)!, animated: false)
Upvotes: 6
Reputation: 5259
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")
Upvotes: 9
Reputation: 5340
If u do not want to type multiple lines of code each time when you want Date or Time from string U can copy below function and use as
let DateVar = DateTimeFrmSrgFnc("31/12/1990",FmtSrg: "dd/MM/yyyy")
timePicker.setDate(DateVar, animated: false)
func DateTimeFrmSrgFnc(DateSrgPsgVar: String, FmtSrg FmtSrgPsgVar: String)-> NSDate
{
// Format: "dd-MM-yyyy HH:mm:ss"
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = FmtSrgPsgVar
return dateFormatter.dateFromString(DateSrgPsgVar)!
}
Upvotes: 0
Reputation: 1580
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)
Upvotes: 5
Reputation: 676
You can customize it by formatting your Date and Time this way:
let dateString = "12-11-2015 10:50:00"
var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "dd-MM-yyyy HH:mm:ss"
let date = dateFormatter.dateFromString(dateString)
timePicker.setDate(date, animated: false)
Upvotes: 4
Reputation: 6413
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)
Upvotes: 20
Reputation: 5183
you can use it like this
timePicker.setDate(NSDate(timeInterval: 60, sinceDate: NSDate()), animated: false)
or
timePicker.setDate(NSDate(timeIntervalSinceNow: 60), animated: false)
it would set date with difference of 1 minute from current date.
Upvotes: 3