开发者

Get all days of any month with objective-c

开发者 https://www.devze.com 2022-12-11 14:57 出处:网络
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

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号