Reputation: 115
I am using date picker with time interval of 30 min. In datePicker it is showing properly with interval of 30. I am getting current time when I picked value from the picker. I am expecting it should be the selected value from the picker not the current time. I am using following code written in Swift 4.
func getTime(sender:UIDatePicker)
{
let dateFormatter = DateFormatter()
dateFormatter.timeStyle = DateFormatter.Style.short
let endDate = (sender.date).addingTimeInterval(TimeInterval(30.0 * 60.0))
let time = dateFormatter.string(from: endDate)
print(“time”) //getting current time like 8:14 AM , expected should be 8:00 AM
}
Upvotes: 1
Views: 5969
Reputation: 1
This is for extract date form date picker:
dateFormatter.dateFormat = "dd/MM/yyyy"
datePicker.datePickerMode = .date
date = dateFormatter.string(from: sender.date)
And this is for extract time from date picker:
dateFormatter.dateFormat = "hh:mm:ss a"
timePicker.datePickerMode = .time
var ouptputTime = dateFormatter.string(from: sender.date)
The most important thing is formatting string. ex("hh:mm:ss a")
Upvotes: -1
Reputation: 163
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.
Upvotes: 5
Reputation: 1
I think this will be helpful.
func getTime(sender:UIDatePicker)
{
var dateFormatter = DateFormatter()
dateFormatter.dateFormat = "hh:mm:ss a"
var ouptputTime = dateFormatter.string(from: sender.date)
print("ouptputTime:-\(ouptputTime)")
}
Upvotes: -2