我如何在 swift 5 中使用两个 UIDatePickers 获取并显示两次之间的差异

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

我是 Swift 的新手,我正在尝试计算 2 个 UIDatePickers the main UI of the app.

之间的时间差

我希望用户能够 select 时间然后按下按钮,显示的时差会显示在 "label" 例如用户选择 5:00 pm 和 11:00 pm 它会显示 6:00 或 6 之类的东西。我不确定我该怎么做。也许像 ( picker1 - picker2 )? 到目前为止,在我的代码中我有:

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

} 

}

这会计算两个日期之间的距离,然后显示小时和分钟。它会忽略秒数,但如果你也需要秒数,你应该能够遵循与我在这里所做的相同的模式。

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

编辑: 虽然这个解决方案有效,但我建议任何寻找解决方案的人使用 但是,您需要更新标签文本,以及我的方式这样做似乎仍然是最好的选择。

使用DateComponents计算两个日期之间的差异:

let date1 = picker1.date
let date2 = picker2.date

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