let time = "14:05"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "HH:mm"
let timeDate = dateFormatter.date(from: time)!
let calendar = Calendar.current
let timeComponents = calendar.dateComponents([.hour, .minute], from: timeDate)
let nowComponents = calendar.dateComponents([.hour, .minute], from: Date())
let difference = calendar.dateComponents([.minute], from: timeComponents, to: nowComponents).minute!
let receivedTimeString = "14:05"
let formatter = DateFormatter()
formatter.dateFormat = "HH:mm"
if let date = formatter.date(from: receivedTimeString) {
// getting the number of minutes in the receivedTimeString:
let receivedTimeHoursMinutes = Calendar.current.component(.hour, from: date) * 60
let receivedTimeMinutes = Calendar.current.component(.minute, from: date)
let totalreceivedTimeMinutes = receivedTimeHoursMinutes + receivedTimeMinutes
// getting the number of minutes in today:
let todayHoursMinutes = Calendar.current.component(.hour, from: Date()) * 60
let todayMinutes = Calendar.current.component(.minute, from: Date())
let todayTimeMinutes = todayHoursMinutes + todayMinutes
// difference in minutes (could be negative):
let difference = totalreceivedTimeMinutes - todayTimeMinutes
print(difference)
}
8条答案
按热度按时间oiopk7p51#
Calendar
有强大的方法来做到这一点。完全不需要任何关于
60
、3600
甚至86400
的显式数学运算。Date
。hour
和minute
日期组件。minute
分量来计算与dateComponents(:from:to:
的差值。eoxn13cs2#
为了得到两个日期之间的分钟差异,我做了下面的事情。
您可以将此方法保留在公共类和调用中。
velaa5lx3#
尽管有各种各样的答案,但我发现Narashima的答案最直接。然而,这里有一个更直接的问题。
x7rlezfr4#
Objective-C版本
Swift版本
5vf7fwbs5#
timeInterval以秒为单位。
如果你想将秒转换为天、小时、分钟和秒:
所以你的字符串是这样的:
guicsvcw6#
请看下面@Alexey Kudley的答案的Swift实现。请给他一些爱的原始解决方案。
vzgqcmou7#
你可以这样得到:
z6psavjg8#
func dateComponents(_ components:设置<Calendar.Component>,从开始:结束日期:Date)-> DateComponents
返回两个日期之间的差值。
let date1 = Date()
let date2 = Date()
let difference = Calendar.current.dateComponents([.minute],from:date1,to:date2).minute