2011-11-09 3 views
0

ウェブサーバーからデータを取得しています。このデータには日付(11-07-1978)があります。私は(int month = 7)のような整数として月を取得したいと思います。文字列を(日付として)分割して文字列の特定の部分を得る(月として)

私は文字列からNSDateを作成し、月をNSDateComponentsのコンポーネントとして取得しようとしました。しかし、私は唯一の値1.

を取得しています。ここに私のコードの抜粋です:

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); 

にはどうすれば整数として、月得ることができますか?ここで

+3

あなたの日付形式は、博覧会とコードの間で一致していない...のがタイプミスすることができるので、これは手が入力されたIT- を行うための迅速かつ汚い方法です - タイプミスということですそれとも実際の問題でしょうか? – 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]; 
関連する問題