2

I have the following code to create NSDate objects from NSString objects.

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"hh:mm aa M/dd/yyyy"];
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithName:@"GMT"]];
NSString *day = @"3/26/2015";
NSString *time = @"10:24 PM";
NSString *dateString = [NSString stringWithFormat:@"%@ %@", time, day];
NSDate *date = [dateFormatter dateFromString:dateString];

This piece of code works perfectly on the simulator, yielding the exact corresponding time in my time zone. However when I run this on a device with iOS 8, date is set to nil.

The format I'm using is supposed to work according to this page that is referenced by this Apple Developer page.

Any help or information on this would be much appreciated. Thanks in advance.

Edit: I'm trying to create NSDate objects from formatted NSString's, not get the date from the system in a predefined fromat. The possible duplicate of this question is probably closely related but I couldn't get the solution to work in my situation.

Edit 2: I've just noticed this problem only occurs when 24-Hour Time is enabled in Settings. However, there is no way for me to know which format the device owner is using, so I'm still in need of a solution.

Community
  • 1
  • 1
halileohalilei
  • 2,220
  • 2
  • 25
  • 52

1 Answers1

3

When working with such strict date formats, you need to set the locale to avoid having issues with the device current locale when formatting dates. Otherwise, the NSDateFormatter will use the device's locale, which explains the fact that it happens only when you enable 24-Hour Time in Settings.

See Apple's documentation:

In all cases, you should consider that formatters default to using the user’s locale (currentLocale) superimposed with the user’s preference settings. If you want to use the user’s locale but without their individual settings, you can get the locale id from the current user locale (localeIdentifier) and make a new "standard” locale with that, then set the standard locale as the formatter's locale.

For example, in your case, you could use the en_US_POSIX:

NSLocale *enUSPOSIXLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];
dateFormatter.locale = enUSPOSIXLocale;
veducm
  • 5,933
  • 2
  • 34
  • 40