你如何使UIDatePicker成为24小时制

时间:2014-11-09 01:31:56

标签: ios swift

我有一个UIDatePicker设置为分钟然后上午/下午的小时。如何将其设置为像英国一样设置为24小时制?例如,1将是13,并且不会是AM或PM。

3 个答案:

答案 0 :(得分:5)

var datePicker = UIDatePicker()
datePicker.datePickerMode = UIDatePickerMode.Time
datePicker.locale = NSLocale(localeIdentifier: "en_GB") // using Great Britain for this example

答案 1 :(得分:0)

使用Swift 4

我遵循以下方法来帮助我实现无AM / PM的计时。

  

请注意,我正在使用TextField作为Inputview

func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
    showTimePicker()
    return true
}

func showTimePicker() {
    timePicker.datePickerMode = .time
    timePicker.locale = Locale(identifier: "en_GB") // Change to your locale

    let toolbar = UIToolbar();
    toolbar.sizeToFit()
    let doneButton = UIBarButtonItem(title: "Done", style: .plain, target: self, action: #selector(doneTimePicker));
    let spaceButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace, target: nil, action: nil)
    let cancelButton = UIBarButtonItem(title: "Cancel", style: .plain, target: self, action: #selector(cancelTimePicker));

    toolbar.setItems([doneButton,spaceButton,cancelButton], animated: false)

    modifiedHoursTextField.inputAccessoryView = toolbar
    modifiedHoursTextField.inputView = timePicker
}

 @objc func doneTimePicker() {

    let timeFormatter = DateFormatter()
    timeFormatter.dateFormat = "HH:mm"
    modifiedHoursTextField.text = timeFormatter.string(from: timePicker.date)
    self.view.endEditing(true)
}

@objc func cancelTimePicker() {
    self.view.endEditing(true)
}

答案 2 :(得分:-2)

向JAL的答案加分,如果您还希望能够选择“日期”,则可以使用以下内容:

viewDidLoad

deadlineTF.inputView = deadlineDatePicker
deadlineDatePicker.timeZone = NSTimeZone.local
deadlineDatePicker.datePickerMode = UIDatePickerMode.dateAndTime
deadlineDatePicker.locale = Locale(identifier: "tr_TR")
deadlineDatePicker.backgroundColor = UIColor.white
deadlineDatePicker.layer.cornerRadius = 5.0
deadlineDatePicker.layer.shadowOpacity = 0.5
deadlineDatePicker.addTarget(self, action: #selector(onDidChangeDate), for: .valueChanged)

功能:

// called when the date picker called.
@objc func onDidChangeDate(sender: UIDatePicker){
    // date format
    let myDateFormatter: DateFormatter = DateFormatter()
    myDateFormatter.dateFormat = "dd/MM/yyyy  HH:mm"

    // get the date string applied date format
    let mySelectedDate = myDateFormatter.string(from: sender.date)
    deadlineTF.text = mySelectedDate
}