1

我正在使用此代码

int unitFlags =  NSMonthCalendarUnit;   
NSDateComponents *comps = [gregorian components:unitFlags fromDate:startDate toDate:endDate options:0];    
int months = [comps month];

我实际上想要缺少任何想法的月份的名称?

4

1 回答 1

2

我已经通过两种方式解决了这个问题,我不知道哪个更好:(我期待人们对我的答案发表评论)

由于您想要开始日期和结束日期之间的所有月份名称,您可以执行以下操作:

方法一:

NSString *startString=@"23 Jun 2012";
NSString *endString=@"23 Dec 2013";

NSDateFormatter *dateFormatterDDMMMYYYY=[NSDateFormatter new];
[dateFormatterDDMMMYYYY setDateFormat:@"dd MMM yyyy"];

NSDate *startDate=[dateFormatterDDMMMYYYY dateFromString:startString];
NSDate *endDate=[dateFormatterDDMMMYYYY dateFromString:endString];

NSMutableArray *betweenMonths=[NSMutableArray new];
NSDate *tempDate=startDate;
while (tempDate<endDate) {
    NSDateFormatter *dateFormatterMMM=[NSDateFormatter new];
    [dateFormatterMMM setDateFormat:@"MMM"];
    NSString *monthName=[dateFormatterMMM stringFromDate:tempDate];
    [betweenMonths addObject:monthName];

    //tempDate is calculted after storing because you not need the last month.
    NSCalendar *calendar=[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSDateComponents *components=[NSDateComponents new];
    components.month=1;
    tempDate=[calendar dateByAddingComponents:components toDate:tempDate options:0];
}
NSLog(@"Month Name : %@",betweenMonths);

方法二:

NSString *startString=@"23 Jun 2012";
NSString *endString=@"23 Dec 2013";

NSDateFormatter *dateFormatterDDMMMYYYY=[NSDateFormatter new];
[dateFormatterDDMMMYYYY setDateFormat:@"dd MMM yyyy"];

NSDate *startDate=[dateFormatterDDMMMYYYY dateFromString:startString];
NSDate *endDate=[dateFormatterDDMMMYYYY dateFromString:endString];

NSInteger month = [[[NSCalendar currentCalendar] components: NSMonthCalendarUnit
                                                   fromDate: startDate
                                                     toDate: endDate
                                                    options: 0] month];

NSDateFormatter *dateFormatterMMM=[NSDateFormatter new];
[dateFormatterMMM setDateFormat:@"MMM"];
NSString *startMonth=[dateFormatterMMM stringFromDate:startDate];

NSArray *months=@[@"Jan",@"Feb",@"Mar",@"Apr",@"May",@"Jun",@"Jul",@"Aug",@"Sep",@"Oct",@"Nov",@"Dec"];

NSInteger startDateMonth=[months indexOfObject:startMonth];

for (NSInteger i=startDateMonth+1; i<startDateMonth+month; i++) {
    NSLog(@"Moths : %@",months[i%12]); //%12 for checking if i goes beyond 11, as endDate may be more then one year span long

}
于 2013-01-13T09:04:10.430 回答