Search code examples
iosswiftuidatepickerswift5xcode10

How do i get and display the difference between two times using two UIDatePickers in swift 5


I'm new to Swift and I'm trying to calculate a time difference between 2 UIDatePickers the main UI of the app.

I want the user to be able to select the time then press the button and a displayed time difference show up in the "label" for example user picks 5:00 pm and 11:00 pm it would show 6:00 or 6 something like that. I'm not sure how I'm to go about doing it. Like ( picker1 - picker2 ) maybe? so far in my code i have:

import UIKit

class ViewController: UIViewController {

@IBOutlet weak var picker1: UIDatePicker!

@IBOutlet weak var picker2: UIDatePicker!

@IBOutlet weak var lable1: UILabel!


override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
}

@IBAction func buttontap(_ sender: Any) {      

} 

}

Solution

  • Use DateComponents to figure out the difference between two dates:

    let date1 = picker1.date
    let date2 = picker2.date
    
    let diff = Calendar.current.dateComponents([.hour, .minute], from: date1, to: date2)
    print("\(diff.hour!), \(diff.minute!)")