bits about life, coding and stuff
Just had a gotcha trying to compile one of my projects on OS4. NSDateFormatter refused to parse dates, just returned zero.
After further investigation, the problem was an almost unnoticeable difference in the date format:
2010-05-17T19:08:11+02:00
But the unicode standard needs a +0200, thus NO Semicolon.
NSDateFormatter for 10.5 and OS3 just silently quit parsing, and because he then assumed 00 nobody noticed.
The behaviour on 10.6 and OS4 changed to be totally strict now.
Prior to Mac OS 10.6, both NSNumberFormatter’s and NSDateFormatter’s implementation of -getObjectValue:forString:errorDescription: would return YES and a parsed object value if only part of the string could be parsed. This is problematic because with this API you cannot be sure what portion of the string was parsed. For applications linked on or after Mac OS 10.6, this method instead returns an error if part of the string cannot be parsed. You can use -getObjectValue:forString:range:error: to get the old behavior; this method returns the range of the substring that was successfully parsed.
See this code example. The “fix” is code line nr.2 (stringByReplacingOccurrencesOfString)
That’s not a perfect solution, it won’t work in wanky half-hour timezones, but i don’t need to parse such data.
Another solution would be a) using the old parse method (getObjectValue:forString:range:error) or use an NSMutableString to search for the last semicolon to purge.
Note the testDebugStr, that’s the best solution to debug Date Formatters. (so obvious…)
Related posts:
5 Responses to NSDateFormatter and +00:00 parsing
Michael
June 2nd, 2010 at 10:18 am
Thanks for sharing this info, I had very same issue and you solution came in handy.
However, it has one gotcha of its own: it will fail on dates like this: 2010-05-17T19:00:00+02:00 because all occurrences of :00 will be replaced, thus making the string invalid.
This is how you can replace last semicolon only:
stringByReplacingOccurrencesOfString:@”:” withString:@”" options:0 range:NSMakeRange([dateStr length] – 5,5)
Will fix half-timezone issue too.
studpete
June 2nd, 2010 at 11:44 am
Hey Michael, thanks for the fix. I’ll update my code too.
Jesse Trimble
June 22nd, 2010 at 6:39 pm
Good call. I spun my wheels on this problem thinking the date formatter would still compensate for the colon. Thanks for posting.
Doug
December 23rd, 2011 at 6:24 am
yyyy-MM-dd’T'HH:mm:ssZZZ
can be changed to
yyyy-MM-dd’T'HH:mm:ssZZ’:00′
and it will parse fine
Shankar Phadatare
December 28th, 2011 at 12:25 pm
This code helps me a lot.
Thanks for posting amazing code.