Question

I encountered a stranger question. NSDateFormatter can't parse 1988-04-10 to NSDate instance in iOS 6. But it works in iOS 4 and iOS 5. Is it a bug?

Following is the code. It is very simple.

NSArray *values = @[@"1988-04-09", @"1988-04-10", @"1988-04-11"];
NSDateFormatter* df = [[NSDateFormatter alloc] init];
NSLocale *posixLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];
[df setLocale:posixLocale];
[df setDateFormat:@"yyyy'-'MM'-'dd"];
NSLog(@"timeZone:%@, locale:%@", df.timeZone, df.locale.localeIdentifier);
NSDate* date = nil;
for (NSString *value in values) {
    date = [df dateFromString:value];
    NSLog(@"The date is %@", date);
}
[posixLocale release];
[df release];

Following is the result in iOS 4 and iOS 5.

2013-03-19 09:55:32.249 SampleProject[1844:f803] timeZone:Asia/Shanghai (CST (China)) offset 28800, locale:en_US_POSIX
2013-03-19 09:55:32.250 SampleProject[1844:f803] The date is 1988-04-08 16:00:00 +0000
2013-03-19 09:55:32.250 SampleProject[1844:f803] The date is 1988-04-09 16:00:00 +0000
2013-03-19 09:55:32.251 SampleProject[1844:f803] The date is 1988-04-10 15:00:00 +0000

Following is the result in iOS 6.

2013-03-19 09:42:40.824 SampleProject[1455:11303] timeZone:Asia/Shanghai (GMT+08:00) offset 28800, locale:en_US_POSIX
2013-03-19 09:42:40.827 SampleProject[1455:11303] The date is 1988-04-08 16:00:00 +0000
2013-03-19 09:42:40.827 SampleProject[1455:11303] The date is (null)
2013-03-19 09:42:40.828 SampleProject[1455:11303] The date is 1988-04-10 15:00:00 +0000

It is null for 1988-04-10. Is is a bug. Can anyone explain it?

Was it helpful?

Solution

Sunday, April 10th, 00:00 was the switch for Daylight Saving Time in Shanghai that year.

According to the great WWDC 2011 Video: Performing Calendar Calculations this can lead to undefined behavior. In the video Rio de Janeiro is chosen as example for the very same reason.

One workaround could be to add a time, that is save, as 3pm.
Another to do the calculation on NSDateComponents.
Both workarounds are explained in the video.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top