How to set a specific default time to select a date in Swift

Is there a way to set a date picker to display a specific time at startup? I have four date picker instances initiated from four text fields for start, end time, start date, and end date using the squimer / datePickerDialog subclass from GitHub that appears in the UIAlertView.

In my application, the default start time is 7:00 and the default end time is 5:00 PM and will allow the user to configure around this time.

All I see is that you can set datePicker.defaultDate to currentDate, minimumDate or maximumDate and only once. Is it possible to set the string strings sTime = "07:00" and fTime = "17:00" in defaultDate in my calls from ViewController?

Any help would be appreciated.

EDIT: This is how I call the subclass from my viewController

@IBAction func setFT(sender: UITextField) { resignKeyboardCompletely(sender) DatePickerDialog().show("Pick a Finish Time", doneButtonTitle: "Done", cancelButtonTitle: "Cancel", datePickerMode: .Time) { (timeFinish) -> Void in self.dateFormatter.dateFormat = "HH:mm" let finTime = self.dateFormatter.stringFromDate(timeFinish) self.finishTime.text = finTime } defaults.setObject(finishTime.text, forKey: "finishTime") print(finishTime.text) } 

Please note that throughout this, I also try to maintain persistence through NSUser Defaults.

+6
source share
1 answer

You are looking for setting time through a string. If so, you can use date formatting like this.

 let dateFormatter = NSDateFormatter() dateFormatter.dateFormat = "HH:mm" let date = dateFormatter.dateFromString("17:00") datePicker.date = date 

Adding init to the Picker class

 init(time:String) { super.init(frame: CGRectMake(0, 0, UIScreen.mainScreen().bounds.size.width, UIScreen.mainScreen().bounds.size.height)) setupView() let dateFormatter = NSDateFormatter() dateFormatter.dateFormat = "HH:mm" if let date = dateFormatter.dateFromString("17:00") { datePicker.date = date } } 
+17
source

All Articles