Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get all days of any month with objective-c

A seemingly simple question...how can I return a list of days for any specified month?

NSDate *today = [NSDate date]; //Get a date object for today's date
NSCalendar *c = [NSCalendar currentCalendar];
NSRange days = [c rangeOfUnit:NSDayCalendarUnit 
                       inUnit:NSMonthCalendarUnit 
                      forDate:today];

I basically want to use that, but replace today with say, the month of January, so I can return all of those days

like image 737
rson Avatar asked Nov 13 '09 19:11

rson


2 Answers

Carl's answer works on Mac. The following works on Mac or iPhone (no dateWithNaturalLanguageString: available there).

NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [[[NSDateComponents alloc] init] autorelease];

// Set your year and month here
[components setYear:2015];
[components setMonth:1];

NSDate *date = [calendar dateFromComponents:components];
NSRange range = [calendar rangeOfUnit:NSCalendarUnitDay inUnit:NSCalendarUnitMonth forDate:date];

NSLog(@"%d", (int)range.length);
like image 156
nall Avatar answered Nov 20 '22 08:11

nall


You can make your date with pretty much any string:

NSDate *date = [NSDate dateWithNaturalLanguageString:@"January"];

Then the rest of your code will work as-is to give you back the NSRange for the number of days in January.

like image 41
Carl Norum Avatar answered Nov 20 '22 09:11

Carl Norum