16

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

gerry3
  • 21,420
  • 9
  • 66
  • 74
rson
  • 1,455
  • 2
  • 24
  • 43

2 Answers2

60

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);
Iulian Onofrei
  • 9,188
  • 10
  • 67
  • 113
nall
  • 15,899
  • 4
  • 61
  • 65
  • Thanks. Original poster didn't specify, so I wasn't sure. – nall Nov 13 '09 at 19:52
  • yeah...my bad. Should have specified :( – rson Nov 13 '09 at 19:53
  • 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 Nov 13 '09 at 19:57
  • 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 Nov 13 '09 at 20:35
  • 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 Nov 13 '09 at 21:47
  • 2
    in this code what will happened to a february in leap year ? – Raj Mar 06 '12 at 12:31
  • 1
    Given that you specify a date which sets the context for the rangeOfUnit:inUnit:forDate method, I assume it does the right thing (returns 1-29). Try it and verify! – nall Mar 06 '12 at 14:53
  • Actually, in this example year 0001 is used. In order to get the proper value for February in a leap year, the year needs to be set in comps properly. – Bejmax Dec 14 '12 at 03:18
  • 2
    Note that month ranges from 1 to 12 in the above code, not from 0 to 11. – Chris Prince Aug 08 '14 at 21:48
2

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
  • 219,201
  • 40
  • 422
  • 469