Hier ist eine supergenaue NSCalendar
Erweiterung in Swift 2:
extension NSCalendar {
func daysInYear(date: NSDate = NSDate()) -> Int? {
let year = components([NSCalendarUnit.Year], fromDate: date).year
return daysInYear(year)
}
func daysInYear(year: Int) -> Int? {
guard let begin = lastDayOfYear(year - 1), end = lastDayOfYear(year) else { return nil }
return components([NSCalendarUnit.Day], fromDate: begin, toDate: end, options: []).day
}
func lastDayOfYear(year: Int) -> NSDate? {
let components = NSDateComponents()
components.year = year
guard let years = dateFromComponents(components) else { return nil }
components.month = rangeOfUnit(NSCalendarUnit.Month, inUnit: NSCalendarUnit.Year, forDate: years).length
guard let months = dateFromComponents(components) else { return nil }
components.day = rangeOfUnit(NSCalendarUnit.Day, inUnit: NSCalendarUnit.Month, forDate: months).length
return dateFromComponents(components)
}
}
Sie können ihn wie folgt verwenden:
let calendar = NSCalendar.currentCalendar() // I'm using the Gregorian calendar
calendar.daysInYear() // 365 (since it's currently 2015)
calendar.daysInYear(2016) // 366 (leap year!)
Das ist sehr flexibel, da wir nichts über die Länge des Kalenders voraussetzen:
let hebrew = NSCalendar(calendarIdentifier: NSCalendarIdentifierHebrew)
hebrew?.daysInYear(-7) // 354
hebrew?.daysInYear(-100) // 384
Viel Spaß!