我的字符串格式为“Fri Jul 09 17:57:44 +0000 2010”,我需要将其转换为NSDate。
我尝试了一些不成功的操作来转换这个日期,并且想知道是否有人能告诉我如何实现这一目标。
此致
答案 0 :(得分:0)
您是否尝试过强力方法:
这是未经测试的,但应该让您知道该怎么做。
// Set up some helper information
NSArray *monthArray = [NSArray arrayWithObjects:@"Jan", @"Feb", @"Mar",
@"Apr", @"May", @"Jun",
@"Jul", @"Aug", @"Sep",
@"Oct", @"Nov", @"Dec", nil];
NSArray *ordinalArray = [NSArray arrayWithObjects:@"01", @"02", @"03",
@"04", @"05", @"06",
@"07", @"08", @"09",
@"10", @"11", @"12", nil];
NSDictionary *monthOrdinalDictionary = [NSDictionary dictionaryWithObjects:ordinalArray
forKeys:monthArray];
// This is the date string to convert.
dateString = @"Fri Jul 09 17:57:44 +0000 2010";
// Split it into it's components
NSArray *dateComponentArray = [dateString componentsSeparatedByString:@" "];
// Create a new date string from the components in a format that NSDate understands
newDateString = [NSString stringWithFormat:@"%@-%@-%@ %@ %@", [dateComponentArray objectAtIndex:6],
[monthOrdinalDictionary objectForKey:[dateComponentArray objectAtIndex:2]],
[dateComponentArray objectAtIndex:3],
[dateComponentArray objectAtIndex:4],
[dateComponentArray objectAtIndex:5]];
// Create the date from this string
NSDate *dateTime = [NSDate dateWithString:newDateString];
是的,它很丑,但你可以将大部分内容重构为辅助函数。我没有对它进行测试,但您应该知道该怎么做:获取日期字符串,将其转换为NSDate可用于创建日期的字符串,使用此字符串创建NSDate。
至少你会有代码可以使用,如果是性能瓶颈,你可以回去更改它。