ios - dateFromString在ios 6中工作,但不在ios 5中工作

标签 ios objective-c ios5 ios6 nsdate

此代码可在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/

相关文章:

ios - Xamarin 表格 : How to clear old distribution certificate and provisioning profile from ios bundle signing?

iphone - 数据库连接

ios - 清除iOS设备

objective-c - NSImage 到 blob 和 blob 到 NSImage (SQLite, NSData)

iphone - 在 iOS 中获取有关时区更改的通知

ios - 当用户无法向 Twitter 发送消息时我该怎么办

android - iOS 和 Android 设备之间的点对点通信

c++ - NSData、NSDictionary、NSArray 等效项 C++

objective-c - Objective-C中如何在不使用键盘的情况下按下键盘上的按键?

iphone - 如何在iOS中获取用户的国家/地区电话代码?