为什么Swift不接受这个NSCalendar方法调用?

时间:2015-01-02 00:46:38

标签: swift nsdate

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

我试图在几个月内找到两个NSDates之间的差异,但此功能将合作。它一直在抱怨"额外的争论' toDate'在电话",但它肯定应该在那里。

2 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:1)

Swift并不接受0作为options的值,例如Objective-C。请改用nil

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

然后你所要做的就是通过dateComponents.month来获得月数。