2011-11-10 91 views
0

格式化一個NSDate我想從一個字符串創建一個NSDate:錯誤從字符串

NSString *mostRecentMentionMessageTimestamp = [mostRecentMessage valueForKey:@"updated_at"]; 
NSLog(@"%@",mostRecentMentionMessageTimestamp); 
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init]; 
[dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZ"]; 
NSDate *mostRecentMentionDate = [dateFormatter dateFromString:mostRecentMentionMessageTimestamp]; 
NSLog(@"%@",mostRecentMentionDate); 

當我打印我的字符串是: 2011-11-10T07:22:59Z

後我從字符串打印日期並打印它,它是(null)

我在做什麼錯?

+0

可能重複(http://stackoverflow.com/questions/2504992/how-to-convert-a-utc-date-to-nsdate ) –

回答

0

格式幾乎是正確的,使用:

[dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss'Z'"]; 

解決時區問題,使用由@Jef解決方案添加:

[dateFormatter setTimeZone: [NSTimeZone timeZoneWithAbbreviation: @"UTC"]]; 

完整的示例代碼:

NSString *mostRecentMentionMessageTimestamp = @"2011-11-10T07:22:59Z"; 
NSLog(@"input: %@",mostRecentMentionMessageTimestamp); 
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init]; 
[dateFormatter setTimeZone: [NSTimeZone timeZoneWithAbbreviation: @"UTC"]]; 
[dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss'Z'"]; 
NSDate *mostRecentMentionDate = [dateFormatter dateFromString:mostRecentMentionMessageTimestamp]; 
NSLog(@"output: %@",mostRecentMentionDate); 

NSLog輸出T:[?如何轉換UTC日期的NSDate]

input: 2011-11-10T07:22:59Z 
output: 2011-11-10 07:22:59 +0000 
0

您嘗試轉換爲NSDate的字符串值不正確。 「2011-11-10T07:22:59Z」
它應該有一個時區差值來代替「Z」,以使它與日期格式化程序的格式兼容。

例如2011-11-10T07:22:59 + 0430

1

您需要設置時區並在日期格式末尾放置Z。由於你的日期有一個Z,所以它是UTC。所以,你可以使用:

[dateFormatter setTimeZone: [NSTimeZone timeZoneWithAbbreviation: @"UTC"]]; 
[dateFormatter setDateFormat: @"yyyy-MM-dd'T'HH:mm:ss"];