Search code examples
iosobjective-cnsdatensdateformatter

NSDate becomes nil


NSDate becomes nil when I change device time to 24 hour format.

NSString *stampStr = @"10/6/2017 8:57:44 AM";
NSDateFormatter *oldFormatter = [NSDateFormatter new];
[oldFormatter setDateFormat:@"MM/dd/yyyy hh:mm:ss a"];
NSTimeZone *tz = [NSTimeZone timeZoneForSecondsFromGMT:10800]; // GMT+3
[oldFormatter setTimeZone:tz];
NSDate *oldDate = [oldFormatter dateFromString:stampStr];

But it works fine when change to 12 hr format in iPhone device.


Solution

  • You need to set the locale of your NSDateFormatter

    oldFormater.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];