NSDateFormatter在OS 4.0中返回nil

Ato*_*iot 26 iphone nsdateformatter ios4

我在OS 3.x上有以下代码

NSString *stringDate = @"2010-06-21T20:06:36+00:00";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZ"];
NSDate *theDate = [dateFormatter dateFromString:stringDate];
NSLog(@"%@",[dateFormatter stringFromDate:theDate]);
Run Code Online (Sandbox Code Playgroud)

但现在在iOS4模拟器下的最新xcode 3.2.3中,变量theDate为零.

我查看了类引用,并没有看到任何已弃用或使用这些特定方法为iOS4实现不同的内容.我遗漏了什么?

Wer*_*her 41

我发现如果你这样做会有效(见下文).关键是使用方法: - [NSDateFormatter getObjectValue:forString:range:error:]

代替

-[NSDateFormatter dateFromString]

完整的代码:

+ (NSDate *)parseRFC3339Date:(NSString *)dateString 
{
    NSDateFormatter *rfc3339TimestampFormatterWithTimeZone = [[NSDateFormatter alloc] init];
    [rfc3339TimestampFormatterWithTimeZone setLocale:[[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"] autorelease]];
    [rfc3339TimestampFormatterWithTimeZone setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZ"];

    NSDate *theDate = nil;
    NSError *error = nil; 
    if (![rfc3339TimestampFormatterWithTimeZone getObjectValue:&theDate forString:dateString range:nil error:&error]) {
        NSLog(@"Date '%@' could not be parsed: %@", dateString, error);
    }

    [rfc3339TimestampFormatterWithTimeZone release];
    return theDate;
}
Run Code Online (Sandbox Code Playgroud)


dea*_*rne 8

您的设备是24小时制还是12小时制?

这听起来像一个疯狂的问题,但我只是遇到了这个错误 - dateformatter会根据当前的语言环境调整你的格式字符串,其中包括时间格式设置.

您可以通过添加以下行来强制它忽略它们:

dateFormatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];
Run Code Online (Sandbox Code Playgroud)

希望有所帮助.

  • 这对我有用.这个Apple链接解释了所有:http://developer.apple.com/iphone/library/qa/qa2010/qa1480.html (4认同)

Ben*_*zar 5

这段代码将删除额外的冒号,因为AtomRiot描述:

将其转换为:

  • NSString *stringDate = @"2010-06-21T20:06:36+00:00";

至:

  • NSString *stringDate = @"2010-06-21T20:06:36+0000";
// Remove colon in timezone as iOS 4+ NSDateFormatter breaks
if (stringDate.length > 20) {
    stringDate = [stringDate stringByReplacingOccurrencesOfString:@":"
                                                       withString:@""
                                                          options:0
                                                            range:NSMakeRange(20, stringDate.length-20)];
}
Run Code Online (Sandbox Code Playgroud)

有关详细信息,请参阅:https://devforums.apple.com/thread/45837