2012-04-13 49 views
0

我有一個字符串在UTC,我想轉換爲NSDate。不知何故即時得到30分鐘錯誤NSDateFormatter錯誤:不正確的字符串到日期轉換

該字符串是 2012-04-10T00:00:00 + 05:30

轉換後的日期是 2012-04-09 19點00分00秒+ 0000

地方,因爲它本來應該 2012-04-09 18:30:00 +0000

即時通訊使用此功能將字符串轉換爲日期

- (NSDate *)parseRFC3339Date{ 
    NSDateFormatter *rfc3339TimestampFormatterWithTimeZone = [[NSDateFormatter alloc] init]; 
    [rfc3339TimestampFormatterWithTimeZone setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZ"]; 

    NSDate *theDate = nil; 
    NSError *error = nil; 
    if (![rfc3339TimestampFormatterWithTimeZone getObjectValue:&theDate forString:self range:nil error:&error]) { 
     NSLog(@"Date '%@' could not be parsed: %@", self, error); 
    } 

    [rfc3339TimestampFormatterWithTimeZone release]; 
    return theDate; 
} 

回答

2

如果您要創建一個NSRange覆蓋整個字符串,並在以-getObjectValue:forString:range:error:通過其地址,然後你會看到,輸出會很短。解析停在冒號,因爲格式字符串中的'Z'只匹配類似「-0800」(無冒號)的內容。如果您要指定4個Z,'ZZZZ',它將匹配類似「GMT-08:00」的內容。這允許冒號,但需要「GMT」。如果您確定日期字符串的格式,可以嘗試插入「GMT」。

相關問題