获取swift内两次的时间差 3

Get time difference between two times in swift 3

我有 2 个变量,其中我从 datePicker 获得了 2 次,我需要在一个变量上保存它们之间的差异。

    let timeFormatter = DateFormatter()
    timeFormatter.dateFormat = "HHmm"

    time2 = timeFormatter.date(from: timeFormatter.string(from: datePicker.date))!

我试图从他们两个那里得到 timeIntervalSince1970,然后他们减去它们并得到毫秒的差异,我将返回到小时和分钟,但我得到一个非常大的数字,与实际时间。

let dateTest = time2.timeIntervalSince1970 - time1.timeIntervalSince1970

然后我尝试使用 time2.timeIntervalSince(date: time1),但结果毫秒数又比实际时间长得多。

如何获得 2 次之间的正确时差,并以“0823”格式的小时和分钟为 8 小时 23 分钟?

TimeInterval 测量秒,而不是毫秒:

let date1 = Date()
let date2 = Date(timeIntervalSinceNow: 12600) // 3:30

let diff = Int(date2.timeIntervalSince1970 - date1.timeIntervalSince1970)

let hours = diff / 3600
let minutes = (diff - hours * 3600) / 60

进行任何日期数学运算的推荐方法是 CalendarDateComponents

let difference = Calendar.current.dateComponents([.hour, .minute], from: time1, to: time2)
let formattedString = String(format: "%02ld%02ld", difference.hour!, difference.minute!)
print(formattedString)

格式%02ld添加了填充零。

如果您需要在小时和分钟之间使用冒号的标准格式 DateComponentsFormatter() 可能是更方便的方式

let formatter = DateComponentsFormatter()
formatter.allowedUnits = [.hour, .minute]
print(formatter.string(from: time1, to: time2)!)

现在你可以在 swift 5 中以这种方式完成,

func getDateDiff(start: Date, end: Date) -> Int  {
    let calendar = Calendar.current
    let dateComponents = calendar.dateComponents([Calendar.Component.second], from: start, to: end)

    let seconds = dateComponents.second
    return Int(seconds!)
}

要获得两个时间间隔之间 的持续时间,可以使用 -

let time1 = Date(timeIntervalSince1970: startTime)
let time2 = Date(timeIntervalSince1970: endTime)
let difference = Calendar.current.dateComponents([.second], from: time1, to: time2)
let duration = difference.second