dateFromString在iOS 6中,但不会在iOS 5中
问题描述:
此代码在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]);
不工作怎么会错?
答
由于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
尝试从“unformattedDate”中移除':' – rckoenes 2013-03-14 16:09:55
检查您的设备日期格式 – 2013-03-14 16:23:31
iOS 5不支持时区格式的'ZZZZZ'。这是在iOS 6中添加的(实际上它被添加到日期格式的Unicode规范的新版本中,这在iOS 5中不存在)。 – rmaddy 2013-03-14 16:27:22