2

I'm trying to work around the infamous issue whereby NSDateFormatter returns 'am/pm' dates when not required (overrwriting the format string) when the user has their locate time settings as 12hour instead of the default 24 hour

After reading around, it seems the best solution is to set the dateFormatter locale to en_US_POSIX (we are using it for API calls, so need to disregard any user preference)

However, it seem to be ignored?

I have a category as follows:

@implementation NSDateFormatter (Locale)

- (id)initWithSafeLocale {
    static NSLocale* en_US_POSIX = nil;
    self = [self init];
    if (en_US_POSIX == nil) {
      en_US_POSIX = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];
    }
    [self setLocale:en_US_POSIX];
    return self;    
}

@end

Then I call:

sharedInstance.dateFormatter = [[NSDateFormatter alloc] initWithSafeLocale];
[sharedInstance.dateFormatter setDateFormat: @"yyyy-MM-dd HH:mm:ss"];

However, the dates are still printed as

2015-09-28 11:00:00 pm +0000

What am I doing wrong it seems to be ignoring the setLocale?

Ref: What is the best way to deal with the NSDateFormatter locale "feechur"?

Community
  • 1
  • 1
Ben
  • 155
  • 2
  • 12

1 Answers1

2

The issue is simply how you are printing the date using NSLog(). This will call [NSDate description] which will use the user's default locale.

From the docs (of descriptionWithLocale):

If you pass nil, NSDate formats the date in the same way as the description property.

On OS X v10.4 and earlier, this parameter was an NSDictionary object. If you pass in an NSDictionary object on OS X v10.5, NSDate uses the default user locale—the same as if you passed in [NSLocale currentLocale].

Instead you should use the date formatter to print the formatted string.

trojanfoe
  • 120,358
  • 21
  • 212
  • 242