【问题标题】:dateFromString working in ios 6 but not in ios 5dateFromString 在 ios 6 中工作,但在 ios 5 中不工作
【发布时间】:2013-03-03 02:13:53
【问题描述】:

此代码适用于 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]);

有什么问题?

【问题讨论】:

  • 尝试从unformattedDate中删除:
  • 检查您的设备日期格式
  • iOS 5 不支持 ZZZZZ 时区格式。这是在 iOS 6 中添加的(实际上它是添加到 iOS 5 中不存在的日期格式的更新版本的 Unicode 规范中)。
  • @rckoenes 你的方法有效:)

标签: ios objective-c ios5 ios6 nsdate


【解决方案1】:

由于在 iOS 6 中添加了 ZZZZZ 日期格式说明符,因此您无法使用 iOS 5 格式化具有 +99:99 格式的时区的日期。两个版本都支持使用 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”语言环境。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多