Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSDateFormatter seems to have the wrong month

I have this block of code to read in the ISO 8601 Date/Time specification. The problem is that for some reason, the month doesn't work. Every time I convert it month is "01". What am I doing wrong?

NSDateFormatter *UTCDateFormat = [[NSDateFormatter alloc] init];
[UTCDateFormat setDateFormat:@"yyyy-MM-DD'T'HH:mm:ss'Z'"];
[UTCDateFormat setTimeZone:[NSTimeZone timeZoneWithName:@"UTC"]];
[UTCDateFormat setCalendar:[[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease]];
[UTCDateFormat setLocale:[[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"] autorelease]];
NSLog(@"%@", [UTCDateFormat dateFromString:dateString]);

So, for example, if dateString was:

@"2002-03-12T21:13:27Z" 

my output would be:

2002-01-12 21:13:27 +0000

Things I have already tried:

  • Changed MM to LL
  • Tried without setCalendar/setLocale
  • tried with ' around the -
  • switched position of MM around to other places. It never changes anything.
  • Looked all over SO and it appears to work for everyone else.
like image 912
Kivak Wolf Avatar asked Feb 13 '12 20:02

Kivak Wolf


1 Answers

Try this

    [UTCDateFormat setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss'Z'"];

DD is the "Day of the year" not the "Day of a month". A great source for looking up NSDateFormatter formats is this table

like image 127
MGA Avatar answered Sep 24 '22 15:09

MGA