2012-09-17 26 views
0

的月份和年份1年我需要獲取月份名稱和下一年的年份並存儲在數組中。我的意思是說,假設今天是2012年9月,我需要的月份名稱和年份至2013年8月。在我的應用中獲取iPhone的

您能告訴我如何獲得月份和年份嗎? Thanx提前

+1

你不是很清楚。你是否每天或每週需要月/年的東西? – AJMansfield

回答

4

使用NSMonthCalendarUnit的組件參數當前日曆的當前日期以獲取當前月份的編號,例如9月份爲9,然後是當年的NSYearCalendarUnit,例如然後在一個for循環中使用這些函數,該循環使用模數運算來包裝到下一年。

如果for循環中的月份編號小於當前月份,則使用當前年份加1作爲下一年份,否則使用當前年份。

請注意,使用NSMonthCalendarUnit時返回的月份編號從1開始,而monthSymbols的索引編號從零開始。這意味着即使我們從九月份開始,我們從這個數組中獲得的月份是十月,這是我們想要的下一個月。

/* 
next 12 months after current month 
*/ 

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; months < 12; m++){ 

    int nextMonth = m % 12; 

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

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

    months++; 
} 
+0

這不是挑選當前的月份,如何包括這一點。 –

+0

這是正確的 - 請參閱'當月後12個月' – SPA

1

NSDateFormatter爲任何類型的日期(NSDate的)關鍵格式化等

int monthNumber = 09; //September 
NSDateFormatter *df = [[[NSDateFormatter alloc] init] autorelease]; 
NSString *monthName = [[df monthSymbols] objectAtIndex:(monthNumber-1)]; 

打印日期像2012年9月17日

NSDateFormatter *df = [[NSDateFormatter alloc] init]; 
[df setDateStyle:NSDateFormatterLongStyle]; 
[df setTimeStyle:NSDateFormatterNoStyle]; 
NSString *dateString = [df stringFromDate:[NSDate date]]; 
[df release]; 
相關問題