2010-11-19 151 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

相關問題