Чтобы сделать то, что вы хотите, вы должны найти диапазон дней в месяце и месяцы в году для определенного календаря. Эта функция будет делать то, что вам нужно для любого календаря, который использует единицы день / месяц / год (или имеет некоторый эквивалентный сопоставленный):
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;
}
Если вы хотите указать этот год, вы можете назвать его просто как getDaysInYear([NSDate date]);
, или вы можете создать дату из определенного года / других компонентов и передать ее. Вы также можете очень легко повторно реализовать его как вызов метода.