NSDateFormatter returning nil in OS 4.0

I had the following code working on on 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]);

but now in the newest xcode 3.2.3 under the iOS4 simulator, the varialble theDate is nil.

I have looked through the class reference and do not see anything deprecated or implemented differently for iOS4 with these specific methods. What did i leave out?


I found out it works if you do it this way (see below). The key is using the method: - [NSDateFormatter getObjectValue:forString:range:error:]

instead of

-[NSDateFormatter dateFromString]

The complete code:

+ (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;
}

Is your device set to 24 hour or 12 hour clock?

That sounds like an insane question but I've just run into that bug - the dateformatter will adjust your format string according to the current locale which will include the time format settings.

You can force it to ignore them by adding this line :

dateFormatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];

Hope that helps.


This code will remove the extra colon as AtomRiot describes:

Converting it from:

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

  • 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)];
    }
    

    for more details see: https://devforums.apple.com/thread/45837

    链接地址: http://www.djcxy.com/p/35152.html

    上一篇: 如何将XML日期格式转换为Cocoa

    下一篇: NSDateFormatter在OS 4.0中返回零