使用objective-c获取任何月份的所有日子

rso*_*son 16 iphone objective-c nsdate

一个看似简单的问题......我怎样才能返回任何指定月份的天数列表?

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];
Run Code Online (Sandbox Code Playgroud)

我基本上想要使用它,但取而代之today的是1月,所以我可以返回所有那些日子

nal*_*all 60

Carl的回答适用于Mac.以下适用于Mac或iPhone(dateWithNaturalLanguageString:此处不可用).

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);
Run Code Online (Sandbox Code Playgroud)

  • 在这段代码中,闰年2月会发生什么? (2认同)
  • 请注意,上述代码中的月份范围为1到12,而不是0到11. (2认同)