This is probably a problem in your time zone. Note that when parsing a date without time, the time is assumed to be zero. However, some specific times don't exist, usually due to Daylight Saving Time changes (which happen in March around the world) or due to specific local time changes.
For example, in Jordan, the DST change is Apr 1 2016, 00:00 => Apr 1 2016, 01:00
. That means that the time Apr 1 2016, 00:00
does not exist because March 31 2016, 23:59
becomes immediately Apr 1 2016, 01:00
. If the date does not exist, date formatter must return nil
.
You can usually fix the problem by using a preset GMT time zone that does not have this problem, e.g
dateFormatter.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0];
or
dateFormatter.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:[NSTimeZone systemTimeZone].secondsFromGMT];
Note that since you are not parsing time, time zone differences shouldn't affect you.
Steps to reproduce
Set the time zone on your machine to Jordan time zone:
NSString *dateString = @"2016-04-01";
NSDateFormatter* parsingFormatter = [[NSDateFormatter alloc] init];
parsingFormatter.dateFormat = @"yyyy-MM-dd";
NSLog(@"Parsed: %@", [parsingFormatter dateFromString:dateString]); // "(null)"
with time zone fix:
NSString *dateString = @"2016-04-01";
NSDateFormatter* parsingFormatter = [[NSDateFormatter alloc] init];
parsingFormatter.dateFormat = @"yyyy-MM-dd";
parsingFormatter.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0];
NSLog(@"Parsed: %@", [parsingFormatter dateFromString:dateString]); // "2016-04-01 00:00:00 +0000"
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…