What's the easiest way to get number of hours between 2 dates with SwiftDate
lib?
In this case hours could be days / minutes or whatever I'll need next time.
I see I can probably do (date1 - date2) / 60 * 60
but that just does not feel right.
Calendar
can do that:
let calendar = Calendar.current
let components = calendar.dateComponents([.hour], from: date1, to: date2)
let hours = components.hour!
or as one-liner:
let hours = Calendar.current.dateComponents([.hour], from: date1, to: date2).hour!
or as Date
extension:
extension Date {
func hoursSince(date: Date) -> Int
{
return Calendar.current.dateComponents([.hour], from: date, to: self).hour!
}
}
在SwiftDate中,您可以轻松完成
(date1 - date2).in(.hour)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.