2013-01-21 35 views
1

我已經嘗試了很多次將字符串2013-01-27T02:31:47+08:00轉換成NSDate。我通過蘋果發現了formatting guide並複製了它的代碼並嘗試了,但它不起作用。如何格式轉換字符串2013-01-27T02:31:47 + 08:00到NSDate

NSDateFormatter *rfc3339DateFormatter = [[NSDateFormatter alloc] init]; 
    NSLocale *enUSPOSIXLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]; 

    [rfc3339DateFormatter setLocale:enUSPOSIXLocale]; 
    [rfc3339DateFormatter setDateFormat:@"yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'"]; 
    [rfc3339DateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:8]]; 

    // Convert the RFC 3339 date time string to an NSDate. 
    NSDate *date = [rfc3339DateFormatter dateFromString:@"2013-01-27T02:31:47+08:00"]; 

回答

6

您的格式應爲@"yyyy-MM-dd'T'HH:mm:ssZZZZZ"。您只需要在格式化程序不會使用的字母周圍使用單引號。

+0

thx :)'ZZZZZ'它適用於我:) – code4j

1
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init]; 
    [dateFormat setDateFormat:@"yyyy-MM-dd HH:mm:ss"]; 
    [dateFormat setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]]; 

    NSString *dateTimeString = @"2013-01-09 16:00:00"; 
    NSLog(@"DateTimeString = %@", dateTimeString); 

    NSDate *myDate =[dateFormat dateFromString:dateTimeString]; 
    NSLog(@"myDate:   %@", myDate); 

輸出:

dateTimeString = 2013-01-09 16:00:00 
    myDate:  = 2013-01-09 16:00:00 +0000 

要提出一個日期給用戶,轉換的NSDate到的NSString,使用stringFromDate,但沒有設置時區(以便使用本地時區):

NSDateFormatter *dateFormat2 = [[NSDateFormatter alloc] init]; 
    [dateFormat2 setDateFormat:@"yyyy-MM-dd HH:mm:ss"]; 

    NSString *localDateString = [dateFormat2 stringFromDate:myDate]; 
    NSLog(@"localDateString: %@", localDateString); 

輸出:

localDateString: 2013-01-09 17:00:00 
+0

Thx爲您的詳細解釋,但我必須轉換'2013-01-27T02:31:47 + 08:00'的確切格式,因爲它從服務器返回: ) – code4j

相關問題