简体   繁体   中英

Getting current time from datepicker if interval has set for datepicker in Swift

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
}

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.

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)")
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM