davidgagne.net

  • About
  • Archives
  • Twitter
  • Facebook
  • bartender.live
  • GitHub
  • LinkedIn

Time Intervals in Swift 4.0

December 5th, 2017 @ 8:32 pm PST

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!
}

More posts tagged:
development / Programming / swift

More posts categorized:
Programming Software

More posts from:
December 2017 / 2017

Post navigation

Previous Post
Previous Post #FridayFive: Christmas Songs
Next Post
Next Post #FridayFive: Vacations

Search


If credit card debt or student loan payments are killing you, I highly recommend taking a look at SoFi. Their low rates and incredibly quick and simple application process might be just what you need.

  • Take Control of Your Debt

© David Vincent Gagne. All rights reserved. Custom WordPress Theme by Jacket Industries.