You can get the time from DatePicker
based on what you select. But you have to get the initial time rounded off to next interval hour by yourself. You can see the code below it will help you.
In this method we are adding target to the datepicker
to get the time based on our selection and we are also getting the initial time.
override func viewDidLoad() {
super.viewDidLoad()
let currentTime = Date()
let interval = 30
self.getInitialTime(currentTime: currentTime, interval: interval)
datePicker.addTarget(self, action: #selector(getTime(sender:)), for: .valueChanged)
}
This function will calculate the time rounded off to next interval time.
func getInitialTime(currentTime: Date, interval: Int) {
var components = Calendar.current.dateComponents([.minute, .hour], from: currentTime)
let minute = components.minute
let remainder = ceil(Float(minute!/interval))
let finalMinutes = Int(remainder * Float(interval)) + interval
components.setValue(finalMinutes, for: .minute)
guard let finalTime = Calendar.current.date(from: components) else { return }
self.getDate(date: finalTime)
}
In these methods we are calling another function which converts date to the required format.
@objc func getTime(sender: UIDatePicker) {
self.getDate(date: sender.date)
}
func getDate(date: Date) {
let dateFormatter = DateFormatter()
dateFormatter.timeStyle = DateFormatter.Style.short
dateFormatter.timeZone = TimeZone.current
let time = dateFormatter.string(from: date)
print(time)
}
Thanks.