We can reproduce your problem by explicitly setting the time zone to “Brazil / East”:
#import <Foundation/Foundation.h> int main(int argc, const char * argv[]) { @autoreleasepool { NSString *dateString = @"19/10/2014"; NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; dateFormatter.timeZone = [NSTimeZone timeZoneWithName:@"Brazil/East"]; [dateFormatter setDateFormat:@"dd/MM/yyyy"]; NSDate *myDate = [dateFormatter dateFromString:dateString]; NSLog(@"myDate = %@", myDate); } return 0; }
Here's the conclusion:
2014-06-06 14:22:28.254 commandLine[31169:303] myDate = (null)
Since you did not specify a time in the dateString , the system takes midnight. But midnight on this date does not exist in the Brazilian time zone .
Brazil changed from BRT (daylight saving time) to BRST (non-daylight time zone) on October 19, 2014 , skipping directly from the last moment "18/10/2014" to "19/10/2014 01:00:00".
Since "10/19/2014 00:00:00" does not exist, NSDateFormatter returns nil . I think this is bad behavior on the part of NSDateFormatter , but we have to deal with it. -[NSDateFormatter dateFromString:] ultimately calls CFDateFormatterGetAbsoluteTimeFromString , which uses the udat_parseCalendar function from International Components for Unicode Library (icu) to analyze the date.
You can work around the problem by forcing the parser to use midday instead of midnight as the default time. No time zones change in / out of daylight saving time at noon. Let's write a helper function that returns the noon of some arbitrary date in a given time zone:
static NSDate *someDateWithNoonWithTimeZone(NSTimeZone *timeZone) { NSDateComponents *components = [[NSDateComponents alloc] init]; components.timeZone = timeZone; components.era = 1; components.year = 2001; components.month = 1; components.day = 1; components.hour = 12; components.minute = 0; components.second = 0; return [[NSCalendar autoupdatingCurrentCalendar] dateFromComponents:components]; }
Then we set the defaultDate date defaultDate to this noon date:
int main(int argc, const char * argv[]) { @autoreleasepool { NSString *dateString = @"19/10/2014"; NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; dateFormatter.timeZone = [NSTimeZone timeZoneWithName:@"Brazil/East"]; dateFormatter.dateFormat = @"dd/MM/yyyy"; dateFormatter.defaultDate = someDateWithNoonWithTimeZone(dateFormatter.timeZone); NSDate *myDate = [dateFormatter dateFromString:dateString]; NSLog(@"myDate = %@", myDate); } return 0; }
And here is the conclusion:
2014-06-06 14:52:31.939 commandLine[31982:303] myDate = 2014-10-19 14:00:00 +0000
rob mayoff Jun 06 '14 at 19:52 2014-06-06 19:52
source share