NSDateFormatter not working

2019-08-02 23:12发布

Ok I feel kind of dumb asking this, but any idea why this is not working:

 {
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        [formatter setDateFormat:@"mmmm dd, yyyy"];

        NSDate *myDateFromString = [formatter dateFromString:creditDate.text];
         NSLog(@"%@", myDateFromString);
        [self.credit setCertificationDate: myDateFromString];
    }

It returns null

1条回答
一纸荒年 Trace。
2楼-- · 2019-08-02 23:59

Format and string don't match because "m" is minute and "M" is month. So "August 18 2012" can't be interpreted, take "MMMM dd yyyy" instead You can check formats at unicode.org

I always set a locale explicitly:

  NSLocale *usLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
  [dateFormatter setLocale:usLocale];
  [usLocale release];

As long as you don't parse month names, it doesn't matter if your real locale is en_US if supplying an explicit format string.

Some more hints:

  • Use a hard coded strings for testing to rule out that the supplied date is wrong.
  • Try easier formatter strings like without time or month as number to isolate the erroneous part.
  • If it is still not working,you can use NSDateFormatter's getObjectValue:forString:range:error: to get more detailed information about the error.
查看更多
登录 后发表回答