aherlambang aherlambang - 11 months ago 88
Objective-C Question

dateFromString always returns null with dateformatter

I have the following code:

NSDateFormatter * df = [[NSDateFormatter alloc] init];
[df setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
[df setTimeZone:[NSTimeZone systemTimeZone]];
[df setFormatterBehavior:NSDateFormatterBehaviorDefault];

[df dateFromString:@"2011-04-12 10:00:00"];

In which it always generates a null date. Why is this?


Are you doing this in a background thread? I had weird experiences with NSDateFormatter when not being used in the ui-thread. Anyway, here's the method I use, should work for you:

+ (NSDate*)parseDate:(NSString*)inStrDate format:(NSString*)inFormat {
    NSDateFormatter* dtFormatter = [[NSDateFormatter alloc] init];
    [dtFormatter setLocale:[NSLocale systemLocale]];
    [dtFormatter setDateFormat:inFormat];
    NSDate* dateOutput = [dtFormatter dateFromString:inStrDate];
    [dtFormatter release];
    return dateOutput;