我有一个格式的字符串@“2011年1月3日凌晨4:55”。请问任何人请告诉我使用NSDateFormatter将上面的字符串转换为NSDate?
答案 0 :(得分: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/