2012-02-05 82 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"];