如何用静态时间计算当前时间和昨天日期之间的时间差
问题描述:
我有一个当前时间和一个静态时间(例如 - 昨天晚上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)")
答
试试这个: -
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)
您可以根据您的要求更改格式。
答
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)
您好,我在let comps = cal.dateComponents([。hour,.minute,.second],from:date,to:staticTime)中忘记了“没有更多上下文的表达式的类型是模糊的” – Arun
您需要将'statcTime'变量初始化为'Date' –