iOS-获得超过2年的月和年

时间:2014-04-09 05:11:26

标签: ios nsdatecomponents nsdatecomponent

我是iOS的新手,我很难在2年内获得数月和数年的时间。我将它们放入NSArray。我所能得到的只有一年,但除此之外,这些年不会增加以反映年份的变化。请帮忙?感谢

NSDate  *todayDate = [NSDate date];
NSDateComponents *todayComponents=[[NSCalendar currentCalendar]      components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit fromDate:todayDate];
NSMutableArray  *monthNameArray   = [[NSMutableArray alloc] init];

int currentMonth = [todayComponents month];
int currentYear = [todayComponents year];
int nextYear = currentYear + 1;

int month = 1;
int year;
for(int m = currentMonth ; month <= 12; m++){

    int nextMonth = m % 12;

    if(nextMonth < currentMonth){
        year = nextYear;
    } else {
        year = currentYear;
    }
    NSString *allMonths = [NSString stringWithFormat:@"%@ %d",[[dateFormatter monthSymbols]objectAtIndex:nextMonth], year];
    [monthNameArray addObject:allMonths];
    month++;

1 个答案:

答案 0 :(得分:0)

for循环在经历12次迭代之前退出,因为它是用currentMonth而不是1初始化的,所以结果是没有得到明年的月份。此外,for循环不会超过12,所以你不会超过12个月 - 这不是两年。

int month = currentMonth-1; // Make zero-based for use with monthSymbols
int year = currentYear;
for(int m = 0 ; m < 24; m++){

    if (month > 11) 
    {
      // The month has transitioned to the next year
      month = 0;
      ++year;
    }
    NSString *allMonths = [NSString stringWithFormat:@"%@ %d",[[dateFormatter monthSymbols]objectAtIndex:month], year];
    [monthNameArray addObject:allMonths];
    month++;