In order to do what you want you have to find the range of days in a month and months in a year for a specific calendar. This function will do what you need for any calendar that uses day/month/year units (or has some equivalent mapped):
NSInteger getDaysInYear(NSDate* date)
{
// Get the current calendar
NSCalendar* c = [NSCalendar currentCalendar];
// Find the range for days and months in this calendar
NSRange dayRange = [c rangeOfUnit:NSDayCalendarUnit inUnit:NSYearCalendarUnit forDate:date];
NSRange monthRange = [c rangeOfUnit:NSMonthCalendarUnit inUnit:NSYearCalendarUnit forDate:date];
// Get the year from the suppled date
NSDateComponents* yearComps = [c components:NSYearCalendarUnit fromDate:date];
NSInteger thisYear = [yearComps year];
// Create the first day of the year in the current calendar
NSUInteger firstDay = dayRange.location;
NSUInteger firstMonth = monthRange.location;
NSDateComponents* firstDayComps = [[[NSDateComponents alloc] init] autorelease];
[firstDayComps setDay:firstDay];
[firstDayComps setMonth:firstMonth];
[firstDayComps setYear:thisYear];
NSDate* firstDayDate = [c dateFromComponents:firstDayComps];
// Create the last day of the year in the current calendar
NSUInteger lastDay = dayRange.length;
NSUInteger lastMonth = monthRange.length;
NSDateComponents* lastDayComps = [[[NSDateComponents alloc] init] autorelease];
[lastDayComps setDay:lastDay];
[lastDayComps setMonth:lastMonth];
[lastDayComps setYear:thisYear];
NSDate* lastDayDate = [c dateFromComponents:lastDayComps];
// Find the difference in days between the first and last days of the year
NSDateComponents* diffComps = [c components:NSDayCalendarUnit
fromDate:firstDayDate
toDate:lastDayDate
options:0];
// We have to add one since this was subtraction but we really want to
// give the total days in the year
return [diffComps day] + 1;
}
If you want to specify this year, you can call it simply as getDaysInYear([NSDate date]);
, or you could create a date from specific year/other components and pass that. You could also very easily re-implement it as a method call.