tags:

views:

36

answers:

2
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_CH

My aDateFromString is coming as nil. What is wrong with my code?

+1  A: 

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.

aBitObvious
I think you are right. In my aKey I am getting "lun,Oct 11, 2010". So you mean to say I should change it to "lun.,octobre 11, 2010"? and add one more M in date formatter?
Abhinav
Yes, aKey needs to be in that format if you want the date formatter to interpret it correctly. If possible, get date strings as yyyy-MM-dd to avoid spelling issues.
aBitObvious
A: 

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];
Dave Klotz
Perfect! It worked for me. Thank you sir.
Abhinav