NSDateFormatter如何格式化这个日期?

时间:2012-08-21 04:01:34

标签: iphone objective-c cocoa-touch nsdateformatter

我正在尝试格式化NSString,如下所示:

  

@ “2012-07-19T02:58:33Z”

到具有以下格式的NSDate:

  

@“MMMM dd,yyyy HH:mm a”

NSDateFormatter总是返回nil,我认为这是因为它无法将当前格式的NSString转换为所需格式。这是我的代码:

 NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
        [formatter setDateFormat:@"MMMM dd, yyyy HH:mm a"];
        NSLocale *enUSLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
        [formatter setLocale:enUSLocale];
        NSDate *date = [formatter dateFromString:dateString];

我是否需要以不同的格式存储日期?我可以使用当前的NSString进行转换吗?

谢谢!

3 个答案:

答案 0 :(得分:1)

你的dateFormatter与你的dateString不匹配...试试这个

NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
[formatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss'Z'"];
NSLocale *enUSLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
[formatter setLocale:enUSLocale];
NSDate *date = [formatter dateFromString:dateString];

[formatter setDateFormat:@"MMMM dd, yyyy HH:mm a"];
dateString=[formatter stringFromDate:date];

现在dateString包含“2012年7月19日02:58 AM”

希望这有帮助

答案 1 :(得分:1)

试试吧。

NSString *myDateString=@"2012-07-19T02:58:33Z";//@"2009-07-06T17:42:12";
NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];

[dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss'Z'"];
 NSDate *myDate = [[NSDate alloc] init];
 myDate = [dateFormatter dateFromString:myDateString];
 NSLog(@"MyDate is: %@", myDate);

答案 2 :(得分:0)

您的问题已经answered

将字符串存储在NSDate中,格式为原始字符串:

NSString *originalDateString = @"2012-07-19T02:58:33Z";
NSDateFormatter *originalFormatter = [[NSDateFormatter alloc]init];
 [formatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss'Z'"];

NSLocale *enUSLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
[formatter setLocale:enUSLocale];
NSDate *originalDate = [formatter dateFromString:originalDateString];

NSDateFormatter *newFormatter = [formatter setDateFormat:@"MMMM dd, yyyy HH:mm a"];
NSString *newDateString = [formatter stringFromDate:originalDate];