NSDateFormatter returning nil NSDate object
NSDateFormatter *aDateFormatter = [[NSDateFormatter alloc] init];
[aDateFormatter setLocale:aLocale];
[aDateFormatter setDateStyle:NSDateFormatterFullStyle];
[aDateFormatter setDateFormat:@"EEE, MMM dd, yyyy"];
NSDate *aDateFromString = [aDateFormatter dateFromString:aKey];
Here, aKey = lun, October 11, 2010
aLocale = fr_开发者_JS百科CHMy aDateFromString
is coming as nil
. What is wrong with my code?
A few things to look at:
- use MMMM (four Ms) instead of MMM if the string contains the full month name
- in fr_CH, MMMM for October is "octobre" ("re" not "er")
- in fr_CH, EEE for Monday is "lun." (period at end)
Make sure aKey is in the proper format and correct the DateFormat string.
Playing around with this for a bit, and this code below gets a legit NSDate:
NSString *df = @"EEE, MMM dd, yyyy";
NSString *ds = @"lun., Octobre 11, 2010";
NSLocale *aLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"fr_CH"];
NSDateFormatter *aDateFormatter = [[NSDateFormatter alloc] init];
[aDateFormatter setLocale:aLocale];
[aDateFormatter setDateStyle:NSDateFormatterFullStyle];
[aDateFormatter setDateFormat:df];
NSDate *aDateFromString = [aDateFormatter dateFromString:ds];
精彩评论