Afin de faire ce que vous voulez, vous devez trouver la gamme de jours dans un mois et des mois dans une année pour un calendrier spécifique. Cette fonction fera ce que vous avez besoin pour un calendrier qui utilise des unités jour/mois/année (ou a un équivalent cartographié):
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;
}
Si vous souhaitez spécifier cette année, vous pouvez l'appeler simplement comme getDaysInYear([NSDate date]);
, ou vous pouvez créer une date à partir d'une année spécifique/d'autres composants et la transmettre. Vous pouvez également très facilement le ré-implémenter en tant qu'appel de méthode.
Il ne fait que vous donner le nombre de jours le mois en cours. Il vous donne en fait la plage de valeurs possibles pour les jours dans l'année avec 1 à 31. Il n'y a pas de date qui pourrait avoir un nombre de jour de 32. –