两个日期之间缺少月份名称

时间:2013-01-13 08:56:00

标签: iphone ios nsdate nscalendar

我正在使用此代码

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

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

1 个答案:

答案 0 :(得分:2)

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

如果你想在开始和结束日期之间命名所有月份,你可以这样做:

方法1:

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);

方法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];

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

}