2011-11-09 4 views
0

웹 서버에서 데이터를 얻고 있습니다. 이 데이터에는 날짜가 있습니다 (예 : 11-07-1978). 저는 달을 정수 (int month = 7)처럼 사용하고 싶습니다.문자열을 (날짜로) 나눔으로써 문자열의 특정 부분을 얻습니다 (한 달 단위)

String에서 NSDate를 만들고 NSDateComponents를 사용하여 구성 요소로 월을 가져 오려고했습니다.

NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease]; 
     dateFormatter.dateFormat = @"yyyy-MM-dd"; 
     NSDate *dateFromString = [dateFormatter dateFromString:[[NSUserDefaults standardUserDefaults] objectForKey:@"result_expdate"]]; 
    NSDateComponents *components = [[NSCalendar currentCalendar] components:NSWeekCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit fromDate:dateFromString]; 
     int day = [components day];  
     int month = [components month]; 
     int year = [components year]; 

NSLog(@"month = %d", month); 

가 어떻게 정수로 월을 얻을 수 있습니다 : 그러나 나는 단지 내 코드의 조각은 값 여기에 1

있어지고있어? 여기

+3

귀하의 날짜 형식은 박람회와 코드 사이에 일치하지 않는 ...의이 오타 할 수 있도록이 손이 입력 한 - 그것을 일을 신속하고 더러운 방법입니다 - 오타이다 아니면 실제 문제일까요? – Tommy

+0

형식이 지정된 날짜가 큰 문자열의 일부라고 말합니다. 주변 콘텐츠와 날짜 부분을 분리하고 코드에서 날짜 부분 및/또는 전체 문자열에 해당하는 변수는 무엇을하고 있습니까? –

답변

1

//chop up the string by "-" 
NSString * dateString = @"11-07-2011"; 
NSArray * tempArray = [dateString componentsSeparatedByString:@"-"]; 

// set string to month 
NSString * monthString = [[tempArray objectAtIndex:1]description]; 

//remove 0's from date if any 
monthString = [monthString stringByReplacingOccurrencesOfString:@"0" withString:@""]; 

//change string to int 
int month = [[NSString stringWithFormat:@"%@",monthString] intValue]; 
관련 문제