One of the things developers need to do with ridiculous frequency is compare two dates. It is mind-boggling to me that doing so in the Swift programming language is so poorly documented. It took dozens of Google searches, endless combing through StackOverflow, and – horror! – reading the actual Apple documentation before I finally stumbled upon a good way to do it.
This function will take two Date() objects and then return the number of hours between them. I’ve left the structure in place so you can alter it to return the number of years, minutes, or seconds if that’s what you need instead. (Some enterprising soul might want to modify the input variables so you can specify which interval type is returned.)
It took me an absurdly long time to discover how to do this, so I’m posting it here for the next developer that wants to do something similar.
If date1
is 2017-12-05 14:22:00 and date2
is 2017-12-05 16:22:00, the function will return 2, which is perfect because there are two hours between those two dates.
func compareDate(date1:Date, date2:Date) -> Int { let units = Set<Calendar.Component>([.hour, .year, .minute, .second]) let cal = NSCalendar.current let return_value = cal.dateComponents(units, from: date1, to: date2) return return_value.hour! }