使用NSDateFormatter格式化日期问题

时间:2011-09-09 18:18:41

标签: iphone objective-c cocoa-touch nsdate nsdateformatter

我有以下日期:

2011-09-09T18:01:47Z

我希望它显示为

"9/9/11 at 1:47PM"无论正确的时间是什么

此代码返回一个空字符串:

NSLog(@"TIME: %@",[message valueForKey:@"created_at"]);
    NSString* time = [message valueForKey:@"created_at"];
    NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"MM-dd-yy at HH:mm:ss"];
    NSDate* newTime = [dateFormatter dateFromString:time];
    [dateFormatter setDateFormat:@"MM-dd-yy at HH:mm:ss"];
    NSString* finalTime = [dateFormatter stringFromDate:newTime];

1 个答案:

答案 0 :(得分:3)

两者的格式相同,与输入和输出几乎没有关系。遇到问题时,请参阅Unicode Data Format Patterns

NSString *datein = @"2011-09-09T18:01:47Z";

NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
//The Z at the end of your string represents Zulu which is UTC
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
[dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss'Z'"];
NSDate* newTime = [dateFormatter dateFromString:datein];

//Add the following line to display the time in the local time zone
[dateFormatter setTimeZone:[NSTimeZone systemTimeZone]];
[dateFormatter setDateFormat:@"M/d/yy 'at' h:mma"];
NSString* finalTime = [dateFormatter stringFromDate:newTime];
NSLog(@"%@", finalTime);