Chei
Chei

Reputation: 2157

980 seconds lost when using NSDateFormatter to convert timezones

When parsing dates in different time zones I noticed that NSDateFormatter produces strange results when working with dates far in the past.

I have the following code:

NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
NSLocale *usLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
[dateFormatter setLocale:usLocale];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm"];

NSString* dateString1 = @"1890-09-30 12:00";
NSString* dateString2 = @"1890-10-01 12:00";

NSLog(@"original timezone %@", [dateFormatter timeZone]);

NSDate* localDate1 = [dateFormatter dateFromString:dateString1];
NSDate* localDate2 = [dateFormatter dateFromString:dateString2];
NSLog(@"localDate1 %@ » %@", dateString1, localDate1);
NSLog(@"localDate2 %@ » %@", dateString2, localDate2);

[dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];

NSDate* utcDate1 = [dateFormatter dateFromString:dateString1];
NSDate* utcDate2 = [dateFormatter dateFromString:dateString2];
NSLog(@"utcDate1   %@ » %@", dateString1, utcDate1);
NSLog(@"utcDate2   %@ » %@", dateString2, utcDate2);

I'm expecting localDates to be one whole hour less than the UTC times, since my timezone is CET. Instead I get this:

original timezone Europe/Budapest (CEST) offset 7200 (Daylight)
localDate1 1890-09-30 12:00 » 1890-09-30 10:43:40 +0000
localDate2 1890-10-01 12:00 » 1890-10-01 11:00:00 +0000
utcDate1   1890-09-30 12:00 » 1890-09-30 12:00:00 +0000
utcDate2   1890-10-01 12:00 » 1890-10-01 12:00:00 +0000

After some investigation it seems like the bug appears for dates earlier than 1890-09-30 23:43.

What's the reason for this? Is it a bug in iOS date handling?

Upvotes: 3

Views: 469

Answers (1)

Thilo
Thilo

Reputation: 262714

The wonderful world of time zones:

When local standard time was about to reach Monday, 1 October 1890, 00:00:00 clocks were turned backward 0:16:20 hours to Sunday, 30 September 1890, 23:43:40 local standard time instead

http://www.timeanddate.com/worldclock/clockchange.html?n=50&year=1890

Upvotes: 6

Related Questions