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 curren开发者_StackOverflowtCalendar];
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
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);
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.
精彩评论