想知道将“yyyymmdd”这样的字符串转换为格式为“mm-dd-yyyy”的字符串的最佳方法。尝试NSDateFormatter没有运气。任何帮助表示赞赏!
我的解决方案如下:
NSString *dateString = @"22082011;
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyyMMdd"];
NSDate *date = [dateFormatter dateFromString:dateString];
[dateFormatter setDateFormat:@"MMM d, YYYY"];
dateString = [dateFormatter stringFromDate:date];
[dateFormatter release];
答案 0 :(得分:7)
您首先需要解析它:
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"yyyyMMdd"];
NSDate *date = [dateFormat dateFromString:dateStr];
然后你可以使用它:
[dateFormat setDateFormat:@"yyyy-MM-dd"];
NSString *myFormattedDate = [dateFormat stringFromDate:date];
答案 1 :(得分:3)
NSString *dateStr = @"20081122";
// Convert string to date object
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"yyyyMMdd"];
NSDate *date = [dateFormat dateFromString:dateStr];
// Convert date object to desired output format
[dateFormat setDateFormat:@"EEEE MMMM d, YYYY"];
dateStr = [dateFormat stringFromDate:date];
[dateFormat release];