Reputation: 51
I have code:
NSString *str = @"1981-04-01";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd"];
NSDate *back = [dateFormatter dateFromString:str];
NSLog("output: %@", back); //output (null)
When i try different dates:
str = @"1982-04-01"; //also return nil
str = @"1985-04-01"; //thats looks good, output: 1985-03-31 20:00:00 +0000
Looks like my timezone is GMT+4. Testing in simulator: xcode 6.3, ios 8.3 (iphone5s)
Why NSDateFormatter returns sometimes nil?
I believe its something to do with my Region: Estonia. Images about OSX and iOS region settings.
(source: ignis.ee)
(source: ignis.ee)
RESOLVED: must be daylight saving switch issue. Please read behind @Matthias Bauch comments.
Upvotes: 2
Views: 253
Reputation: 3389
I would suggest you to just set up the time zone to GMT like
dateFormatter.timeZone = [NSTimeZone timeZoneWithAbbreviation:@"GMT"];
The full code from your view like. .
NSString *str = @"1981-04-01";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.timeZone = [NSTimeZone timeZoneWithAbbreviation:@"GMT"];
[dateFormatter setDateFormat:@"yyyy-MM-dd"];
NSDate *back = [dateFormatter dateFromString:str];
NSLog(@"output: %@", back);
Your output like
output: 1981-04-01 00:00:00 +0000
Upvotes: 2