2012-02-05 81 views
3

从NSString的格式化我有以下字符串表示日期&时间日期使用NSDateFormatter

NSString *shortDateString = @"Sat28Apr2012 15:00"; 

(没有空格(除了在前面的时候一个空格),就如同它是上面)

我想用格式化此日期:

NSDateFormatter *inputFormatter = [[NSDateFormatter alloc] init]; 
// Question is regarding the line below: 
[inputFormatter setDateFormat:@"EEE, d MMM yyyy HH:mm"]; 

NSDate *formatterDate = [inputFormatter dateFromString:shortDateString]; 

NSDateFormatter *outputFormatter = [[NSDateFormatter alloc] init]; 
NSTimeZone *gmt = [NSTimeZone timeZoneWithAbbreviation:@"GMT"]; 
[outputFormatter setTimeZone:gmt]; 
[outputFormatter setDateFormat:@"dd.MMM.yyyy HH:mm Z"]; 

NSString *newDateString = [outputFormatter stringFromDate:formatterDate]; 
+0

您的字符串缺少有关年份的信息。 – dasblinkenlight 2012-02-05 11:27:04

+0

是的,固定的那 – chewy 2012-02-05 11:31:19

+0

那么年份和时间之间是否有空格,或者“没有空格,就像上面一样”评论仍然适用? – dasblinkenlight 2012-02-05 11:33:02

回答

3

如果改变哟你的字符串稍微匹配你输入的格式,它的工作正常。所有你需要做的就是去掉空格和字符串中的逗号,像这样:

"EEEdMMMyyyy HH:mm" 

有了这个字符串我得到下面的结果:

08.Apr.2012 19:00 +0000 

这是19:00,不15:00,因为我时区比格林威治标准时间晚四小时。

+0

干杯队友,赞赏 – chewy 2012-02-05 12:06:22

1
[inputFormatter setDateFormat:@"EEEddMMMyyyy HH:mm"];