Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 483
aherlambang Avatar asked Apr 12 '11 16:04

aherlambang


4 Answers

If the device is set to AM/PM time and requested string format is set to @"yyyy-MM-dd HH:mm:ss" dateFromString will return nil.

If you set the locale to @"en_US" conversion will return correct date.

dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setTimeZone:[NSTimeZone timeZoneWithName:@"GMT"]];
[dateFormat setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]];
[dateFormat setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSDate *date = [dateFormat dateFromString:@"2013-02-14 09:30:00"];
like image 147
Alex Avatar answered Oct 27 '22 21:10

Alex


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;
}
like image 35
Jan Gressmann Avatar answered Oct 27 '22 21:10

Jan Gressmann


I had the same issue. I started by double-checking that the string used for conversion was valid by using this resource.

I then had a thought that it might be the locale, so I tried the following:

[dateFomatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_AU"]]

It worked like a charm. Hope this helps.

like image 8
Marcus Thornton Avatar answered Oct 27 '22 22:10

Marcus Thornton


I just ran this code and it worked for me.

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

NSDate *theDate = [df dateFromString:@"2011-04-12 10:00:00"];
NSLog(@"date: %@", theDate);

The output was: date: 2011-04-12 17:00:00 +0000

like image 4
NWCoder Avatar answered Oct 27 '22 21:10

NWCoder