-3

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) {      

} 

}
terahertz
  • 2,915
  • 1
  • 21
  • 33
moss s
  • 3
  • 1

2 Answers2

2

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

Gereon
  • 17,258
  • 4
  • 42
  • 73
-1

This computes the distance between the two dates, then displays the hours and minutes. It ignores seconds, but if you need seconds as well, you should be able to follow the same pattern as what I did here.

let firstDate = picker1.date
let secondDate = picker2.date
let timeInBetween = secondDate.timeIntervalSince(secondDate) //this is in seconds

var hours = 0
var minutes = 0
var seconds = timeInBetween
while seconds >= 3600 {
    seconds -= 3600
    hours += 1
}
while seconds >= 60 {
    seconds -= 60
    minutes += 1
}

lable1.text = "\(hours) hour\(hours == 1 ? "" : "s"), \(minutes) minute\(minutes == 1 ? "" : "s")."

EDIT: Although this solution works, I suggest anyone looking for a solution uses @Gereon's solution instead. You will need to update the label text, however, and my way of doing that still appears to be the best option.

Sam
  • 2,350
  • 1
  • 11
  • 22