使用timeIntervalSince(_ anotherDate: Date)
函数获取两个日期之间的差异。
func findDateDiff(time1Str: String, time2Str: String) -> String {
let timeformatter = DateFormatter()
timeformatter.dateFormat = "hh:mm a"
guard let time1 = timeformatter.date(from: time1Str),
let time2 = timeformatter.date(from: time2Str) else { return "" }
//You can directly use from here if you have two dates
let interval = time2.timeIntervalSince(time1)
let hour = interval / 3600;
let minute = interval.truncatingRemainder(dividingBy: 3600) / 60
let intervalInt = Int(interval)
return "\(intervalInt < 0 ? "-" : "+") \(Int(hour)) Hours \(Int(minute)) Minutes"
}
调用该函数两次以查找差异。
let dateDiff = findDateDiff(time1Str: "09:54 AM", time2Str: "12:59 PM")
print(dateDiff)
如果你有2个Date
对象,可以使用以下方法获取它们之间的时间差(也称为Double
):
let difference = date1.timeIntervalSince(date2)
DateComponentsFormatter
,可以像这样使用:let differenceDescription = dateComponentsFormatter.string(from: difference)
let differenceDescription = dateComponentsFormatter.string(from: date1, to: date2)
与所有格式化程序一样,不要每次需要使用它们时都创建它们。它们是非常耗费资源的对象,应该保存以便重复使用。
let difference = Calendar.current.dateComponents([.hour, .minute], from: time1, to: time2)
let formattedString = String(format: "%02ld%02ld", difference.hour!, difference.minute!)
print(formattedString)
格式%02ld会添加前导零。
第二条
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