Doug Smith
Doug Smith

Reputation: 29316

Why will Swift not accept this NSCalendar method call?

let dateComponents = NSCalendar.currentCalendar().components(.MonthCalendarUnit, fromDate: dateCreated, toDate: NSDate(), options: 0)

I'm trying to find the difference between two NSDates in months, but this function will not cooperate. It keeps complaining about "extra argument 'toDate' in call", but it's definitely supposed to be there.

Upvotes: 0

Views: 346

Answers (2)

Emil
Emil

Reputation: 7256

Swift doesn't accept 0 as a value for options, like Objective-C. Use nil instead:

let dateComponents = NSCalendar.currentCalendar().components(.MonthCalendarUnit, fromDate: dateCreated, toDate: NSDate(), options: nil)

Then all you have to do is get the number of months by doing dateComponents.month.

Upvotes: 1

Leo Dabus
Leo Dabus

Reputation: 236315

extension NSDate {
    func monthsFrom(date:NSDate) -> Int{
        return NSCalendar.currentCalendar().components(.CalendarUnitMonth, fromDate: date, toDate: self, options: nil).month
    }
}

let dateX = NSCalendar.currentCalendar().dateWithEra(1, year: 2014, month: 11, day: 28, hour: 5, minute: 9, second: 0, nanosecond: 0)!
let dateY = NSCalendar.currentCalendar().dateWithEra(1, year: 2015, month: 1, day: 1, hour: 22, minute: 51, second: 0, nanosecond: 0)!

let months = dateY.monthsFrom(dateX)  // 1

Upvotes: 2

Related Questions