设置日期后,还要在文本字段上设置时间

时间:2019-06-28 05:43:37

标签: ios swift

我正在像这样在文本字段中设置日期...

override func viewDidLoad() {
    super.viewDidLoad()
   showDatePicker()
  }

 func showDatePicker() {

    datePickerStartDate.datePickerMode = .date

    datePickerStartDate.addTarget(self, action: #selector(EventDetailViewController.startDatePickerSelect(sender:)), for: .valueChanged)

    startDateTextfield.inputView = datePickerStartDate

  }

 @objc func startDatePickerSelect(sender: UIDatePicker)  {

    let formatter = DateFormatter()
    formatter.dateStyle = .medium

    startDateTextfield.text = formatter.string(from: sender.date)

  }

这将在文本字段上点击时打开日期选择器并设置日期。但是我想要的是在选择日期之后,也希望时间选择器也显示出来,以便我也可以设置时间。并且此时间应附加到最初设置的日期。我该如何实现呢??

1 个答案:

答案 0 :(得分:0)

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "hh:mm"

您可以从字符串中获取您选择的时间:

let timeStr = "2:00"
var time = dateFormatter.dateFromString(timeStr)

或者您也可以从当前日期中添加或减去特定时间:

//It will give you the time by adding 5 minutes to the current time you can use (-5*60) to get the time 5 minute back.

var date = Date().addingTimeInterval(TimeInterval(5*60))
var timeStr = dateFormatter.string(from: date)