iphone中NSDateFormatter模擬器可以正常顯示,但在真機上不行睦优,轉(zhuǎn)換后的NSString為NULL辙浑,部分代碼如下:
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
NSString *dateStr = @"Dec 29, 2016 11:19:39 PM";
NSDate *date = [self dateFromString:dateStr];
NSLog(@"%@",date); //模擬器上正常,真機打出來為Null
NSLog(@"%@",[self stringFromDate:date]);
}
//NSDate轉(zhuǎn)NSString
-(NSString *)stringFromDate:(NSDate *)date
{
NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setLocale:locale];
//設(shè)置格式:zzz表示時區(qū)
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
//NSDate轉(zhuǎn)NSString
NSString *currentDateString = [dateFormatter stringFromDate:date];
//輸出currentDateString
NSLog(@"%@",currentDateString);
return currentDateString;
}
//NSString轉(zhuǎn)NSDate
-(NSDate *)dateFromString:(NSString *)string
{
NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init] ;
[formatter setLocale:locale];
[formatter setDateFormat:@"MMM dd, yyyy K:mm:ss aa"];
//NSString轉(zhuǎn)NSDate
NSDate *date=[formatter dateFromString:string];
return date;
}
找了半天微王,終于找到原因:
在真機運行需要設(shè)置Local,添加下面一段代碼就OK:
NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
[formatter setLocale:locale];