views:

896

answers:

2

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

+1  A: 

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.

Carl Norum
+8  A: 

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

NSCalendar* cal = [NSCalendar currentCalendar];
NSDateComponents* comps = [[[NSDateComponents alloc] init] autorelease];

// Set your month here
[comps setMonth:1];

NSRange range = [cal rangeOfUnit:NSDayCalendarUnit
                          inUnit:NSMonthCalendarUnit
                         forDate:[cal dateFromComponents:comps]];
NSLog(@"%d", range.length);
nall
I'll give a +1 to that. =)
Carl Norum
Thanks. Original poster didn't specify, so I wasn't sure.
nall
yeah...my bad. Should have specified :(
rson
What if I wanted to go a step further and use a date formatter and loop through each one of those days and return for instance, "Thursday 17th"
rson
Not sure I understand, but I think you're saying you have an NSDate from an NSDateFormatter. You want to get the NSDateComponents via NSCalendar's componentsFromDate method, passing NSWeekdayCalendarUnit(Thurs) and NSDayCalendarUnit (17) as the flags.
nall
Picture this scenario: you have a table view listing out all of the months of the year. When you choose April, a new tableview is presented with all of the days of April, formatted as such "Monday, 1" "Tuesday, 2" etc.
rson