On comparing two Date() objects in XCode

Time Intervals in Swift 4.0

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!
Note: If you are a SwiftUI developer, you need to get Core Data Mastery from Big Mountain Studio. You'll learn everything you need to take your apps to the next level.

Post the first comment:

I'll never share your email address and it won't be published.

What Is This?

davidgagne.net is the personal weblog of me, David Vincent Gagne. I've been publishing here since 1999, which makes this one of the oldest continuously-updated websites on the Internet.


A few years ago I was trying to determine what cocktails I could make with the alcohol I had at home. I searched the App Store but couldn't find an app that would let me do that, so I built one.


You can read dozens of essays and articles and find hundreds of links to other sites with stories and information about Ernest Hemingway in The Hemingway Collection.