2010-11-19 92 views
3
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"); 
} 

我在iPhone中使用24小时设置。在更改为24小时设置后,datefromstring始终返回nil。我改为12小时格式,它再次工作。为什么?dateFromString返回零后更改24小时

回答

5

需要设置语言环境以避免受到24小时设置更改的影响。
格式还具有用于匹配输入字符串(在您的示例包括日期):

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"); 
} 

更多信息参见QA1480