I'm trying to get the number of days in a current year.
When I try the solution on Number of days in the current month using iPhone SDK?, and replace NSMonthCalendarUnit by NSYearCalendarUnit, I still get the number of days for that month.
Does anyone know how I should do this?
Thanks in advance for your help.
Here's a super accurate NSCalendar
extension 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)
}
}
You can use it like this:
let calendar = NSCalendar.currentCalendar() // I'm using the Gregorian calendar
calendar.daysInYear() // 365 (since it's currently 2015)
calendar.daysInYear(2016) // 366 (leap year!)
This is super flexible since we don't assume anything about the length of the calendar:
let hebrew = NSCalendar(calendarIdentifier: NSCalendarIdentifierHebrew)
hebrew?.daysInYear(-7) // 354
hebrew?.daysInYear(-100) // 384
Enjoy.
If you're only going to use the Gregorian Calender, you can calculate it manually.
http://en.wikipedia.org/wiki/Leap_year#Algorithm
if year modulo 400 is 0 then leap
else if year modulo 100 is 0 then no_leap
else if year modulo 4 is 0 then leap
else no_leap
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With