NSDateFormatter returns null for specific dates

I have a problem with NSDateFormatter . It returns null for some specific dates.

I performed this function to debug the case:

 - (void) debugTest:(NSString *)dateStr{ NSLog(@"String: %@", dateStr); NSDateFormatter *df = [[NSDateFormatter alloc] init]; [df setDateFormat:@"yyyy-MM-dd"]; NSDate *dateObj = [df dateFromString: dateStr]; NSLog(@"Date: %@", dateObj); } 

This is my log output for some dates:

 String: 2012-10-18 Date: 2012-10-18 03:00:00 +0000 String: 2012-10-19 Date: 2012-10-19 03:00:00 +0000 String: 2012-10-20 Date: 2012-10-20 03:00:00 +0000 String: 2012-10-21 Date: (null) String: 2012-10-22 Date: 2012-10-22 02:00:00 +0000 String: 2012-10-23 Date: 2012-10-23 02:00:00 +0000 

Why does it return null only for the date 2012-10-21 ?

I conducted other tests with an interval from 2011-10-01 to 2014-11-01 , and the following dates returned null :

 2011-10-16, 2012-10-21, 2013-10-20, 2014-10-19 

It's some kind of mistake? Am I doing something wrong?

+6
source share
1 answer

I will answer my question in order to register if someone gets the same problem:

I added in my date format [df setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]]; And [df setTimeZone:[NSTimeZone timeZoneWithName:@"GMT"]]; .

So my new code is:

 - (void) debugTest:(NSString *)dateStr{ NSLog(@"String: %@", dateStr); NSDateFormatter *df = [[NSDateFormatter alloc] init]; [df setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]]; [df setTimeZone:[NSTimeZone timeZoneWithName:@"GMT"]]; [df setDateFormat:@"yyyy-MM-dd"]; NSDate *dateObj = [df dateFromString: dateStr]; NSLog(@"Date: %@", dateObj); } 

I think the problem is with the device configuration, setting two properties that fixed the problem.

+4
source

Source: https://habr.com/ru/post/926663/


All Articles