此代码可在iOS 6.0模拟器上运行,但不能在iOS 5.0上运行
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]);
有什么事吗
最佳答案
由于ios 6中添加了ZZZZZ
日期格式说明符,因此您无法在iOS 5中使用+99:99
格式格式化具有时区的日期。这两个版本均使用+9999
支持ZZZZ
格式。如果您知道日期/时间字符串中的冒号始终带有时区,则可以删除冒号。
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”语言环境。
关于ios - dateFromString在ios 6中工作,但不在ios 5中工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15414201/