Ali Zahr Ali Zahr - 16 days ago 4x
Objective-C Question

objective-c dateFromString returns nil on specific date

The date is always nil, but if I change the dateString to any other date like 03/01/1975 it works normally. Any idea?

NSString *dateString = @"05/01/1975";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
NSLocale *gbLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"us"];
[dateFormatter setLocale:gbLocale];
[dateFormatter setDateFormat:@"MM/dd/yyyy"];
NSDate *date = [dateFormatter dateFromString:dateString];


Try this

NSString *dateString = @"05/01/1975";
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setTimeStyle:NSDateFormatterShortStyle];
[formatter setTimeZone:[NSTimeZone timeZoneWithName:@"UTC"]];
[formatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]];
 [formatter setDateFormat:@"MM.dd.yyyy"];
NSDate *anotherDate = [formatter dateFromString:dateString];

It will give output like this

1975-05-01 00:00:00 +0000