2013-03-14 62 views
1

此代碼在iOS 6.0模擬器工作的工作,但在iOS 5.0dateFromString在iOS 6中,但不會在iOS 5中

NSString *unformattedDate = @"2008-09-25T20:41:11.000+00:00"; 
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; 
[dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ"]; 
NSDate *dateFromString = [dateFormatter dateFromString:unformattedDate]; 
[dateFormatter setDateFormat:@"dd.MM.yy"]; 
NSLog(@"%@", [dateFormatter stringFromDate:dateFromString]); 

不工作怎麼會錯?

+2

嘗試從「unformattedDate」中移除':' – rckoenes 2013-03-14 16:09:55

+0

檢查您的設備日期格式 – 2013-03-14 16:23:31

+1

iOS 5不支持時區格式的'ZZZZZ'。這是在iOS 6中添加的(實際上它被添加到日期格式的Unicode規範的新版本中,這在iOS 5中不存在)。 – rmaddy 2013-03-14 16:27:22

回答

4

由於ZZZZZ日期格式說明在iOS 6中添加的,你不能格式化必須在+99:99格式與iOS 5時區日期,這兩個版本都支持使用ZZZZ+9999格式。如果你知道你的日期/時間字符串將總是帶有冒號的時區,那麼你可以去掉冒號。

NSString *unformattedDate = @"2008-09-25T20:41:11.000+00:00"; 
NSRange range = [unformattedDate rangeOfString:@":" options:NSBackwardsSearch]; 
if (range.location != NSNotFound && range.location >= unformattedDate.length - 4) { 
    unformattedDate = [unformattedDate stringByReplacingCharactersInRange:range withString:@""]; 
} 
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; 
NSLocale *posix = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]; 
[dateFormatter setLocale:locale]; 
[dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSSZZZZ"]; 
NSDate *dateFromString = [dateFormatter dateFromString:unformattedDate]; 
[dateFormatter setDateFormat:@"dd.MM.yy"]; 
NSLog(@"%@", [dateFormatter stringFromDate:dateFromString]); 

需要注意的是有固定格式這樣,你必須格式化的語言環境設置爲特殊的「en_US_POSIX」區域。

+0

它的工作原理!萬分感謝 – user1248568 2013-03-15 08:07:33