两个UIDatePicker之间的间隔时间不同

时间:2017-07-29 11:09:58

标签: ios swift xcode uidatepicker

我有两个 UIDatePicker ,我希望显示两次 所以,如果我选择时间为 4:30 ,那么在另一个UIDatePicker中它将从6:30显示,所以我想要2小时间隔时间

那么任何人都可以解决这个问题吗?

请帮帮我。

  let datePickerView  : UIDatePicker = UIDatePicker()
  datePickerView.datePickerMode = UIDatePickerMode.time
  txtFrom.inputView = datePickerView
  datePickerView.addTarget(self, action: #selector(datePickerValueChanged), for: .valueChanged)




func datePickerValueChanged(sender: UIDatePicker) {
    let timeFormatter = DateFormatter()
    timeFormatter.timeStyle = .short
    txtFrom.text = timeFormatter.string(from: sender.date)
    let datePickerTo  : UIDatePicker = UIDatePicker()
    datePickerTo.datePickerMode = UIDatePickerMode.time
    let date1 = timeFormatter.date(from: txtFrom.text!)
    datePickerTo.minimumDate = date1?.addingTimeInterval(60 * 60 * 2)
    txtTo.inputView = datePickerTo
    datePickerTo.addTarget(self, action: #selector(datePickerValueChangedTO), for: .valueChanged)


}


func datePickerValueChangedTO(sender: UIDatePicker) {
        if Validate .isEmpty(txtFrom.text) {
            Util.invokeAlertMethod("ReHydration", strBody: "Please Select From Time", delegate: nil)
            return
        }
        else
        {
            let timeFormatter = DateFormatter()
            timeFormatter.timeStyle = .short
            txtTo.text = timeFormatter.string(from: sender.date)
            let date1 = timeFormatter.date(from: txtFrom.text!)
            let date2 = timeFormatter.date(from:  txtTo.text!)

            let calender:Calendar = Calendar.current
            let components: DateComponents = calender.dateComponents([.hour, .minute ], from: date1!, to: date2!)
            print(components)
            var returnString:String = ""
            print(components.minute!)
            if components.hour! <= 120 && components.minute! <= 60 {
                returnString = "Just Now"
            }else if components.minute! >= 1{
                returnString = String(describing: components.minute) + " min ago"
            }else if components.hour! >= 1{
                returnString = String(describing: components.hour) + " hour ago"
            }

        }
}

1 个答案:

答案 0 :(得分:0)

是的,您可以使用addingTimeInterval方法实现此功能。

定义变量以存储第一个datepicker的日期。

var fromTime: Date?

完成从datePickerView选择日期后,将datePickerView.date保存到fromTime变量。

之后,对于该DatePicker的datePickerTo设置minimumDate属性,如下所示。

datePickerTo.minimumDate = fromTime?.addingTimeInterval(60 * 60 * 2) // 2 hour interval

因此,它会打开日期选择器,它比datePickerView提前2小时。

希望你能得到你的想法。