NSDateFormatter case sensitive trap

Thu, 03. Dec 2009

Categories: en development Tags: Cocoa iPhone NSDateFormatter Objective C OS X SenTestingKit Unicode

Though NSDateFormatter behaves slightly different than documented, the following might even be correct, as strange as it might look (mind the last two lines):

    NSDateFormatter *lower = [[[NSDateFormatter alloc] init] autorelease];
    lower.dateFormat = @"yyyy-MM-dd HH:mm:SS ZZZ";

    NSDateFormatter *upper = [[[NSDateFormatter alloc] init] autorelease];
    upper.dateFormat = @"YYYY-MM-dd HH:mm:SS ZZZ";

    lower.timeZone = upper.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0];

    NSDate *d = [lower dateFromString:@"1970-01-01 00:00:00 +0000"];
    STAssertEqualObjects(@"1970-01-01 00:00:00 +0000", [lower stringFromDate:d], @"lower iso wrong");
    STAssertEqualObjects(@"1970-01-01 00:00:00 +0000", [upper stringFromDate:d], @"upper iso wrong");

    d = [d addTimeInterval:(-60*60)];

    STAssertEqualObjects(@"1969-12-31 23:00:00 +0000", [lower stringFromDate:d], @"lower iso wrong");
    STAssertEqualObjects(@"1970-12-31 23:00:00 +0000", [upper stringFromDate:d], @"upper iso wrong");

The Unicode Format Pattern Documentation explains the difference of the upper- and lowercase year format โ€“ but frankly I don’t get the „Year of week of year“ idea.

But that subtracting one hour in fact adds almost a whole year โ€“ that’s odd to me.

So I rather stay away from the uppercase form โ€“ be it correct or buggy.

Seen with iPhone SDK 3.1.2 and XCode 3.2.1 on Snow Leopard.


I think I got it! Uppercase YYYY makes sense only in combination with a calendar week โ€“ and not months or quarters.

Look at January 1st 2010. It belongs to calendar week 53 of 2009. Week 1 / 2010 starts on Jan 4th.