let dateComponents = NSCalendar.currentCalendar().components(.MonthCalendarUnit, fromDate: dateCreated, toDate: NSDate(), options: 0)
我试图在几个月内找到两个NSDates之间的差异,但此功能将不合作。它一直在抱怨"额外的争论' toDate'在电话",但它肯定应该在那里。
答案 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
来获得月数。