views:

1412

answers:

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?

+3  A: 

[Edit: I didn't notice the "iphone" tag on the question; the iPhone only supports the 10.4+ style, so the suggestion below doesn't apply to the iPhone, but I'll leave it in case people using the non-iPhone version find this question down the road]

You are using the new-style (10.4+) format strings, but NSDateFormatter uses the 10.3-and-earlier behavior by default, and the format strings are completely different. You need to either call:

[format setFormatterBehavior:NSDateFormatterBehavior10_4];

after you create it, or call this somewhere earlier in your application:

[NSDateFormatter setDefaultFormatterBehavior:NSDateFormatterBehavior10_4];

(Many of Apple's examples assume the latter; sometimes they mention that, but other times they don't, which can make their examples confusing.)

smorgan
I tried this, and it doesn't seem to make a difference. I get the same output.
Mike Akers
Did you set the behavior before calling setDateFormat:?
Chuck
+5  A: 

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
Bingo! That fixed it.
Mike Akers