我有两个 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"
}
}
}
答案 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小时。
希望你能得到你的想法。