2011-01-03 19 views
2

@ "Jan 3rd、2011 4:55 am"の形式の文字列があります。 NSDateFormatterを使用して上記の文字列をNSDateに変換するよう教えてください。ここでNSStringからNSString

答えて

1

私はそれを行うだろうかです:

NSDateFormatter *format = [[NSDateFormatter alloc] init]; 

[format setDateFormat:@"MMM d, yyyy h:mm a"]; 
NSString *strDate = @"Jan 3rd, 2011 4:55 am"; 
removeUnwantedCharactersFromDateString(&strDate); 
NSDate *date = [format dateFromString:strDate]; 

[format release]; 

removeUnwantedCharactersFromDateString機能(私は:)無駄に長い名前の王だ)ここからの援助の

void removeUnwantedCharactersFromDateString(NSString **str) 
{ 
    NSString *str1 = *str; 
    NSRange seekrange = NSMakeRange(5, [str1 rangeOfString:@","].location - 5); 

    NSRange range = [str1 rangeOfString:@"st" options:NSCaseInsensitiveSearch range:seekrange]; 
    if (range.location != NSNotFound) 
     goto END; 
    range = [str1 rangeOfString:@"nd" options:NSCaseInsensitiveSearch range:seekrange]; 
    if (range.location != NSNotFound) 
     goto END; 

    range = [str1 rangeOfString:@"rd" options:NSCaseInsensitiveSearch range:seekrange]; 
    if (range.location != NSNotFound) 
     goto END; 

    range = [str1 rangeOfString:@"th" options:NSCaseInsensitiveSearch range:seekrange]; 
    if (range.location == NSNotFound) 
    { 
     [NSException raise:@"Invalid operation" format:@"The string is in the incorrect format"]; 
     return; 
    } 

END: 
    *str = [str1 stringByReplacingCharactersInRange:range withString:@""]; 
} 

ロット:

http://www.stepcase.com/blog/2008/12/02/format-string-for-the-iphone-nsdateformatter/