Get all days of any month with objective-c

后端 未结 2 980
没有蜡笔的小新
没有蜡笔的小新 2020-12-14 19:23

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
N         


        
相关标签:
2条回答
  • 2020-12-14 19:48

    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 讨论(0)
  • 2020-12-14 19:57

    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);
    
    0 讨论(0)
提交回复
热议问题