NSDateFormatter在OS 4.0中返回零
我有以下代码在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]);
但现在在iOS4模拟器下的最新xcode 3.2.3中,变量theDate为零。
我已经浏览了类参考,并没有发现任何不赞成使用这些特定方法的iOS4或实现不同的方法。 我放弃了什么?
  如果你这样做,我发现它的工作原理(见下文)。  关键是使用方法: - [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;
}
您的设备是否设置为24小时制或12小时制?
这听起来像是一个疯狂的问题,但我刚刚遇到该错误 - dateformatter将根据当前的语言环境调整格式字符串,其中将包括时间格式设置。
你可以强制它通过添加下面这行来忽略它们:
dateFormatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];
希望有所帮助。
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)];
}
有关更多详细信息,请参阅:https://devforums.apple.com/thread/45837
链接地址: http://www.djcxy.com/p/35151.html上一篇: NSDateFormatter returning nil in OS 4.0
下一篇: What is the difference between 'typedef' and 'using' in C++11?
