I'm wondering if there is some new and awesome possibility to get the amount of days between two NSDates in Swift / the "new" Cocoa?
E.g. like in Ruby I would do:
(end_date - start_date).to_i
I'm wondering if there is some new and awesome possibility to get the amount of days between two NSDates in Swift / the "new" Cocoa?
E.g. like in Ruby I would do:
(end_date - start_date).to_i
Here is my answer for Swift 2:
There's hardly any Swift-specific standard library yet; just the lean basic numeric, string, and collection types.
It's perfectly possible to define such shorthands using extensions, but as far as the actual out-of-the-box APIs goes, there is no "new" Cocoa; Swift just maps directly to the same old verbose Cocoa APIs as they already exist.
Update for Swift 3 iOS 10 Beta 4
I translated my Objective-C answer
result
The hardest part was that the autocompletion insists fromDate and toDate would be
NSDate?
, but indeed they must beNSDate!
as shown in the reference.I don't see how a good solution with an operator would look like, as you want to specify the unit differently in each case. You could return the time interval, but than won't you gain much.
Here is very nice,
Date
extension to get difference between dates in years, months, days, hours, minutes, secondsI see a couple Swift3 answers so I'll add my own:
The naming feels more Swifty, it's one line, and using the latest
dateComponents()
method.