2

I'm trying to parse a string that was generated by an NSDateFormatter using another NSDateFormatter with the same format.

Rather than trying to make that previous sentence make sense, here's some code:

NSDateFormatter *format = [[NSDateFormatter alloc] init];
[format setDateFormat:@"MMM dd, YYYY HH:mm"];

NSDate *now = [[NSDate alloc] init];

NSString *dateString = [format stringFromDate:now];

NSDateFormatter *inFormat = [[NSDateFormatter alloc] init];
[inFormat setDateFormat:@"MMM dd, YYYY HH:mm"];

NSDate *parsed = [inFormat dateFromString:dateString];

NSLog(@"\n"
      "now:        |%@| \n"
      "dateString: |%@| \n"
      "parsed:     |%@|", now, dateString, parsed);

When I run this code, I expect that parsed would contain the same date as now but instead I get the following output:

now:        |2009-05-04 18:23:35 -0400| 
dateString: |May 04, 2009 18:23| 
parsed:     |2008-12-21 18:23:00 -0500|

Anybody have any ideas why this is happening?

Mike Akers
  • 12,039
  • 14
  • 58
  • 71

1 Answers1

9

Your problem is that "YYYY" isn't a valid ICU date formatting option. You want "yyyy".

Capital 'Y' is only valid when used with the "week of year" option (i.e. "'Week 'w' of 'Y").

Matt Gallagher
  • 14,858
  • 2
  • 41
  • 43