dateFromString return nil after change 24 hour

2019-02-19 04:39发布

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'm using 24 hour setting in iPhone. After I change to 24 hour setting, datefromstring always return nil. I rechange to 12 hour format, it's working again. Why ?

1条回答
你好瞎i
2楼-- · 2019-02-19 05:19

The locale needs to be set to avoid being affected by the 24-hour setting change.
The format also has to 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 more information.

查看更多
登录 后发表回答