2012-09-17 2 views
0

내 앱에서 다음 1 년 동안 월 이름과 연도를 가져와 배열에 저장해야합니다. 2012 년 9 월의 오늘을 가정 해 보겠습니다. 2013 년 8 월까지 월 이름과 연도가 필요합니다.iPhone에서 1 년 전월의 월 및 연도 가져 오기

월과 연도를 어떻게 알 수 있습니까? 미리 고맙습니다

+1

매우 명확하지 않습니다. 당신은 매주 또는 매주 또는 한 달/일 년이 필요합니까? – AJMansfield

답변

4

사용 NSMonthCalendarUnit을 날짜를 인쇄하려면 현재 달의 수를 얻기 위해 현재 달력의 예 9 월은 9이고 그 다음 현재 연도의 NSYearCalendarUnit입니다. 그런 다음 모듈러스 산술을 사용하는 for 루프에서 다음 연도로 랩핑합니다.

for 루프의 월 번호가 현재 달보다 작 으면 다음 연도로 현재 연도와 1을 더한 다음 현재 연도를 사용하십시오.

NSMonthCalendarUnit을 사용할 때 반환되는 월 번호는 1에서 시작하지만 monthSymbols의 인덱스 번호는 0부터 시작합니다. 9 월 9 일부터 9 월까지 시작한다고해도, 우리가이 배열에서 얻는 달은 10 월인데 이는 우리가 원하는 다음 달입니다.

/* 
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)]; 

구성 요소 매개 변수에 대해 9 월 17 일 같은 2012

NSDateFormatter *df = [[NSDateFormatter alloc] init]; 
[df setDateStyle:NSDateFormatterLongStyle]; 
[df setTimeStyle:NSDateFormatterNoStyle]; 
NSString *dateString = [df stringFromDate:[NSDate date]]; 
[df release]; 
관련 문제