Search code examples
iosobjective-cnsdateformatter

NSDate returning NULL when debugging in phone


This NSDate able to get the show when i debugging in simulator from xcode. But when I debugging in iphone6 it show NULL.

NSString *dateWithTime = [NSString stringWithFormat:@"2019/03/18 09:30 AM"];

    NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
    fmt.dateFormat = @"yyyy-MM-dd hh:mm a";
    [fmt setAMSymbol:@"am"];
    [fmt setPMSymbol:@"pm"];

    fmt.timeZone = [NSTimeZone systemTimeZone];
    NSDate *localDate = [fmt dateFromString:dateWithTime];
    NSLog(@"DATE -- %@ ", [fmt stringFromDate:localDate]);

No idea is it because the phone timezone not using am/pm or any other causes.

Kindly please help me answer it.


Solution

  • Try setting the locale for the date formatter

    fmt.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
    

    Update

    For en_US_POSIX locale you can use:

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