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):

 1-(void)testNSDateFormatterTrap
 2{
 3    NSDateFormatter *lower = [[[NSDateFormatter alloc] init] autorelease];
 4    lower.dateFormat = @"yyyy-MM-dd HH:mm:SS ZZZ";
 5
 6    NSDateFormatter *upper = [[[NSDateFormatter alloc] init] autorelease];
 7    upper.dateFormat = @"YYYY-MM-dd HH:mm:SS ZZZ";
 8
 9    lower.timeZone = upper.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0];
10
11    NSDate *d = [lower dateFromString:@"1970-01-01 00:00:00 +0000"];
12    STAssertEqualObjects(@"1970-01-01 00:00:00 +0000", [lower stringFromDate:d], @"lower iso wrong");
13    STAssertEqualObjects(@"1970-01-01 00:00:00 +0000", [upper stringFromDate:d], @"upper iso wrong");
14
15    d = [d addTimeInterval:(-60*60)];
16
17    STAssertEqualObjects(@"1969-12-31 23:00:00 +0000", [lower stringFromDate:d], @"lower iso wrong");
18    STAssertEqualObjects(@"1970-12-31 23:00:00 +0000", [upper stringFromDate:d], @"upper iso wrong");
19}

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.

Update:

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.