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

I need to change the UIDatePicker to a specific one dynamically.

My date selection is set in time mode only. I can set the time using

timePicker.setDate(NSDate(), animated: false) 

but I can’t understand how to change it to another time, and not to Current time.

So how do I change it?

thanks

+5
source share
6 answers

You have to change the time , you can do it with NSDateComponents and set the changed date to 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) 
+9
source

You can configure it by formatting the date and time as follows:

 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) 
+3
source

To set the date (time) only at a specific time, for example "09:00", I would install NSDateComponents and the collector.

 let calendar = NSCalendar.currentCalendar() let components = NSDateComponents() components.hour = 9 components.minute = 0 timePicker.setDate(calendar.dateFromComponents(components)!, animated: true) 
+3
source

you can use it like this:

 timePicker.setDate(NSDate(timeInterval: 60, sinceDate: NSDate()), animated: false) 

or

 timePicker.setDate(NSDate(timeIntervalSinceNow: 60), animated: false) 

it will set the date with a difference of 1 minute from the current date.

+1
source

Swift 3:

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

Using:

 datePicker.setDate(from: "1/1/2000 10:10:00", format: "dd/MM/yyyy HH:mm:ss") 
+1
source

If you do not want to enter several lines of code every time you want the date or time from the string U can copy the function below and use it 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)! } 
0
source

Source: https://habr.com/ru/post/1215135/


All Articles