Trying to set only time in UIDatePicker in Swift 2.0

12,452

Solution 1

Try setting its Mode:

starttimedatePicker.datePickerMode = UIDatePickerMode.Time

Solution 2

This may help you.

let starttimedatePicker = UIDatePicker()
starttimedatePicker.datePickerMode = UIDatePickerMode.Time
startTimeDiveTextField.inputView = starttimedatePicker
starttimedatePicker.addTarget(self, action: #selector(ViewController.startTimeDiveChanged), forControlEvents: .ValueChanged)


func startTimeDiveChanged(sender: UIDatePicker) {
    let formatter = NSDateFormatter()
    formatter.timeStyle = .ShortStyle
    startTimeDiveTextField.text = formatter.stringFromDate(sender.date)
}

If you are using DatePicker in Storyboard or Xib then set like this.

enter image description here

Share:
12,452
Scubadivingfool
Author by

Scubadivingfool

Updated on June 23, 2022

Comments

  • Scubadivingfool
    Scubadivingfool about 2 years

    I am trying to set the UIDatePicker to come up with the time only. The DatePicker comes up through an action when the textfield is pressed. I have not used the DatePicker Viewer. Any help is appreciated. Thanks

    let starttimedatePicker = UIDatePicker()
        startTimeDiveTextField.inputView = starttimedatePicker
        starttimedatePicker.addTarget(self, action: "startTimeDiveChanged:", forControlEvents: .ValueChanged)
    
    
    func startTimeDiveChanged(sender: UIDatePicker) {
        let formatter = NSDateFormatter()
        formatter.timeStyle = .ShortStyle
        startTimeDiveTextField.text = formatter.stringFromDate(sender.date)
    }
    
  • Scubadivingfool
    Scubadivingfool over 8 years
    Damn, knew it was something easy. Not a good way to start the new year. Thanks
  • Marcelo
    Marcelo over 8 years
    You might wanna set it as the answer so it can help other people as well. I am glad I could help! :)
  • Scubadivingfool
    Scubadivingfool over 8 years
    Sorry, not enough coffee today