Search code examples
iosswiftnscalendar

Pretty Date Intervals in Swift. NSCalendar components


I'm trying to print a prettier version of a timeIntervalSinceDate e.g '10 days, 6 hours...'. But i'm failing to get NSCalendar components to work correctly.

I get an "Extra argument 'toDate' in call" error with the following:

let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "EE, dd MMM y hh:mm a zzz"

var dateString = "Wed, 08 Jun 2011 11:58 pm EDT"

var date: NSDate = dateFormatter.dateFromString(dateString)!

var now = NSDate()

let calendar: NSCalendar = NSCalendar()

let components = calendar.components(unitFlags: .CalendarUnitDay,
                                      fromDate: date,
                                        toDate: now,
                                       options: 0)

components.day

The 'toDate' feature is documented, so I'm not sure why I get the error?

Any help appreciated.


Solution

  • There are two errors:

    • The first parameter in a method does not have an external parameter name, so you must not specify unitFlags:.
    • For "no options", specify NSCalendarOptions(0) or simply nil.

    Together:

    let components = calendar.components(.CalendarUnitDay,
           fromDate: date, toDate: now, options: nil)
    

    Update for Swift 2: NS_OPTIONS are now imported as conforming to OptionSetType, and "no options" can be specified as the empty set:

    let components = calendar.components(.Day,
        fromDate: date, toDate: now, options: [])