I have a method to convert a string in a specific format into an NSDate
but it occasionally returns nil.
- (NSDate *)dateFromString:(NSString *)dateAndTime
{
NSDate *date;
NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
[formatter setDateFormat:@"MM/dd/yyyy hh:mm a"];
NSTimeZone *gmt = [NSTimeZone timeZoneWithAbbreviation:@"GMT"];
[formatter setTimeZone:gmt];
date = [formatter dateFromString:dateAndTime];
return date;
}
This works most of the time from what I can tell, but there's a percentage of time that it fails.
I've been tracking this bug for a while so there is some code that makes the app crash when this happens. The crash reports tell me the values that made the method return nil.
For example, I received a crash report telling me that "4/14/2015 7:35 PM" returned nil.
When I hard code the same value for every date, it works when running the app in debug mode from my computer.
What could be going on here? Am I not covering some cases for NSDate
s? How come it doesn't happen on every device?