如何用静态时间计算当前时间和昨天日期之间的时间差

时间:2017-08-29 06:32:32

标签: ios swift swift3

我有一个当前时间和一个静态时间(例如 - 昨天晚上9点30分),我需要找到这两次之间的时间差,用hh:mm:ss格式。

这是我用来获取当前时间的代码:

let date = Date()
let calendar = Calendar.current

let hour = calendar.component(.hour, from: date)
let minutes = calendar.component(.minute, from: date)
let seconds = calendar.component(.second, from: date)
print("hours = \(hour):\(minutes):\(seconds)")

2 个答案:

答案 0 :(得分:4)

试试这个: -

    let dateFormatter = DateFormatter()
    var userCalendar = Calendar.current
    userCalendar.timeZone = TimeZone.current
    let requestedComponent: Set<Calendar.Component> = [.hour,.minute,.second]
    dateFormatter.dateFormat = "dd/MM/yy hh:mm:ss"
    let startTime = Date()
    let endTime = dateFormatter.date(from: "28/08/17 08:40:00")
    let timeDifference = userCalendar.dateComponents(requestedComponent, from: endTime!, to: startTime)
    print(timeDifference)
    let date = Calendar(identifier: .gregorian).date(from: timeDifference)
    dateFormatter.dateFormat = "HH:mm:ss"
    let dateString =  dateFormatter.string(from: date!)

    print(dateString)

您可以根据自己的要求更改格式。

答案 1 :(得分:0)

let date = Date()
let cal = Calendar.current
let formatter = DateFormatter()
formatter.dateFormat = "HH:mm:ss"
let staticTime = ...
let comps = cal.dateComponents([.hour, .minute, .second], from: date, to: staticTime)
let diff = cal.date(from: comps)!
let diffString = formatter.string(from: diff)