0

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 NSDates? How come it doesn't happen on every device?

kraftydevil
  • 5,144
  • 6
  • 43
  • 65
  • 1
    "4/14/2014" does not match "MM/dd/yyyy". "04/14/2014" would match. You also need to set the locale to "en_US_POSIX". The need for that is covered in many discussions here and in Apple's documentation. – rmaddy Apr 15 '15 at 00:04
  • http://stackoverflow.com/questions/6613110/what-is-the-best-way-to-deal-with-the-nsdateformatter-locale-feature – Hot Licks Apr 15 '15 at 00:25

1 Answers1

2

First, the date string of 4/14/2015 7:35 PM is possibly M/d/yyyy h:m a or M/dd/yyyy h:mm a. http://www.unicode.org/reports/tr35/tr35-25.html#Date_Format_Patterns

Second, it is recommended to set NSLocale to NSDateFormatter.

formatter.locale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"];

I had a same issue that NSDate was set nil when I worked with a Chinese guy. It happened only on the specific devices, and the problem was region settings.

To reproduce the problem, follow below steps:

  1. go to Settings app
  2. General -> Language & Region -> Advanced
  3. Turn off Automatic
  4. change Language to Chinese, Simplified
  5. execute your app again. You will find NSDate is always nil if NSLocale is NOT set.
Joey
  • 2,912
  • 2
  • 27
  • 32
  • 1
    The locale needs to be "en_US_POSIX", not just "en_US". – rmaddy Apr 15 '15 at 05:38
  • Yep - I was able to reproduce the issue with your suggestions. The only thing I'm not really clear on (even after the doc you posted) is the difference between M and MM. The app seems to be working now that I set the locale, regardless of using MM. – kraftydevil Apr 16 '15 at 03:34