我有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分钟?
答案 0 :(得分:8)
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
答案 1 :(得分:8)
进行任何日期数学运算的推荐方法是Calendar
和DateComponents
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)!)
答案 2 :(得分:3)
要在两个时间间隔之间以秒为单位获取持续时间,可以使用-
let time1 = Date(timeIntervalSince1970: startTime)
let time2 = Date(timeIntervalSince1970: endTime)
let difference = Calendar.current.dateComponents([.second], from: time1, to: time2)
let duration = difference.second
答案 3 :(得分:0)
现在您可以通过这种方式迅速完成5
func getDateDiff(start: Date, end: Date) -> Seconds {
let calendar = Calendar.current
let dateComponents = calendar.dateComponents([Calendar.Component.second], from: start, to: end)
let seconds = dateComponents.second
return Seconds(seconds!)
}