简单的日期格式问题yyyymmdd

时间:2011-08-09 19:37:38

标签: iphone objective-c ios date formatting

想知道将“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];

2 个答案:

答案 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];

来自helpful article.