1

试图从当前月份获取当前年份的下十二个月。下面是我正在尝试的代码,但它是从下个月开始挑选的,所以我对其进行了修改,但现在它显示了 2014 年的当前月份和 2013 年的其他月份。

 NSDateFormatter  *dateFormatter   = [[NSDateFormatter alloc] init];
NSDate           *today           = [NSDate date];
NSCalendar       *currentCalendar = [NSCalendar currentCalendar];

NSDateComponents *monthComponents = [currentCalendar components:NSMonthCalendarUnit fromDate:today];
int currentMonth = [monthComponents month];

NSDateComponents *yearComponents  = [currentCalendar components:NSYearCalendarUnit  fromDate:today];
int currentYear  = [yearComponents year];
int nextYear     = currentYear + 1;

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

int nextMonth = m % 12;

if(nextMonth < currentMonth){
    year = nextYear;
} else {
    year = currentYear;
}

NSLog(@"%@ %i",[[dateFormatter monthSymbols] objectAtIndex: nextMonth],year);

months++;
}

这是下面链接的输出。

August 2013
September 2013
October 2013
November 2013
December 2013
January 2014
February 2014
March 2014
April 2014

2013-07-09 12:54:48.683 MyEventApp[13562:c07] 2014 年 5 月 2013-07-09 12:54:48.683 MyEventApp[13562:c07] 2014 年 6 月 2013-07-09 12:54:48.683 MyEventApp[13562: c07] 2014 年 7 月

从此链接获取帮助获取 iPhone 中提前 1 年的月份和年份。

这是我修改后的代码。

July 2014
August 2013
September 2013
October 2013
November 2013
December 2013
January 2014
February 2014
March 2014
April 2014
May 2014
June 2014
4

1 回答 1

-1

更改此行

if(nextMonth < currentMonth)

if(nextMonth < currentMonth-1)
于 2013-07-09T08:04:02.123 回答