NSDateFormatter not working

怎甘沉沦 提交于 2019-12-11 05:50:01

问题


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:


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.


来源:https://stackoverflow.com/questions/7103150/nsdateformatter-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!