-2

I have a date string which looks like this: Mar 13 '15

I am not able to find the right way to parse this. I've tried the following:

NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:@"MMM dd ''YY"];
//[df setDateFormat:@"MMM dd 'YY"];
//[df setDateFormat:@"MMM dd YY"];
NSDate *date = [df dateFromString:label.text];

Does anyone know how to do it using setDateFormat ? Thanks^^

matrix4use
  • 611
  • 1
  • 6
  • 20
  • try with MMM dd, ''yy instead of MMM dd, ''YY – Duyen-Hoa Mar 13 '15 at 21:10
  • Use lowercase yy. See http://stackoverflow.com/questions/822417/why-cant-i-correctly-parse-this-date-string-with-nsdateformatter. See http://www.unicode.org/reports/tr35/tr35-dates.html#Date_Format_Patterns. –  Mar 13 '15 at 21:10

2 Answers2

2

YY is for year in week based calendars, which is used in some non-gregorian calendars. You generally should use yy instead. See the unicode reference of valid date pattern.

And you should set the locale to en_US_POSIX, to make sure that the date is parsed as a date in the english language. For example in the german locale your conversion would fail because instead of Mar 13 '15 today is März 13 '15.

NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:@"MMM dd ''yy"];
[df setLocale:[NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"]];
Matthias Bauch
  • 89,811
  • 20
  • 225
  • 247
  • It worked :-). Danke for the detailed answer and the side note on locale. There is a tiny error; it should read **localeWithLocaleIdentifier**. – matrix4use Mar 13 '15 at 22:23
0

You are using the wrong style of year, you need to use lowercase y.

        [df setDateFormat:@"MMM d ''yy"];

Uppercase Y is documented as "Year (in "Week of Year" based calendars)." and mentions "May not always be the same value as calendar year". See: http://www.unicode.org/reports/tr35/tr35-31/tr35-dates.html#Date_Format_Patterns

kevin
  • 2,021
  • 21
  • 20