DateFromString returns zero after changing 24 hours

NSDateFormatter *timeFormat = [[NSDateFormatter alloc] init];
[timeFormat setDateFormat:@"hh:mm a"];

NSDate* sourceDate = [timeFormat dateFromString:@"19/11/2010 12:00 am"];
if(sourceDate==nil)
{
    NSLog(@"source date nil");
}

I use the 24 hour setting on the iPhone. After I switch to the 24 hour setting, datefromstring always returns zero. I change to 12-hour format, it works again. What for?

+3
source share
1 answer

The locale must be set so as not to affect the change in the setting within 24 hours.
The format should also match the input string (which in your example includes the date):

NSDateFormatter *timeFormat = [[NSDateFormatter alloc] init];
NSLocale *locale = [[[NSLocale alloc] 
                    initWithLocaleIdentifier:@"en_US_POSIX"] autorelease];  
[timeFormat setLocale:locale];
[timeFormat setDateFormat:@"dd/MM/yyyy hh:mm a"];

NSDate* sourceDate = [timeFormat dateFromString:@"19/11/2010 12:00 am"];
if(sourceDate==nil)
{
    NSLog(@"source date nil");
}

See QA1480 for details .

+5
source

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


All Articles