iOS 4.2 DateFormatter

1.5k views Asked by At

The following code worked in my app previous to iOS 4.2.

NSString *sunday = @"2011-03-13 20:15 -04:00";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm Z"];
NSDate *myDate = [dateFormatter dateFromString:sunday];

NSLog(@"sunday: %@ myDate: %@ fromNow: %d", sunday, myDate, [myDate timeIntervalSinceNow]);

Outputs:

sunday: 2011-03-13 20:15 -04:00 myDate: (null) fromNow: 0

What am I doing wrong here? myDate is null. Is there something about dateFormmater that changed and I'm missing. I imagine it's something trivial at this point as I've been staring at this...

2

There are 2 answers

1
Costique On

If I understand the problem correctly, Z specifier parses both "-0400" and "GMT-04:00", not "-04:00". UTS #35 seems to confirm it. In my tests, though, it even parsed "GMT-0400". So "-04:00" does look like the only time zone format NSDateFormatter refuses to understand.

May I cynically suggest Apple's bug reporter as the answer?

1
Chris Zelenak On

Try quoting your dashes, eg:

  @"yyyy'-'MM'-'dd HH':'mm Z"

My best reading here: http://unicode.org/reports/tr35/tr35-6.html#Date_Format_Patterns seems to suggest that this is actually required, though I seem to recall having used that same date formatting pattern in the past on iOS w/o issue.