吐槽:用户反馈回这个问题的时候,我用测试机测试,没问题,用自己的机子测试OK,(1)排除新机型带来的问题。
然后后台拿到用户数据,在项目上运行,能显示。(2)排除数据格式不正确,
开始模拟用户的数据,人在毛里求斯,设置语言法语,地区毛里求斯,没有问题(保持微笑)
后来同事提醒,试试 12小时制。。。。。(得,问题重现了)于是我开始漫长的求知之路(两天 ^>^)
以上结论:测试环境为地区设置为毛里求斯,12小时制。
源(原)代码:
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
UILabel * label = [[UILabel alloc] initWithFrame:CGRectMake(100, 100, [UIScreen mainScreen].bounds.size.width/2,30)];
label.textColor = [UIColor redColor];
label.text = [self timeTransfer:@"20200427130101"];
[self.view addSubview:label];
NSLog(@"timeTransfer: %@",[self timeTransfer:@"20200427130101"]);
}
-(NSString *)timeTransfer:(NSString *) string{
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyyMMddHHmmss"];
NSDate *date = [dateFormatter dateFromString:string];
[dateFormatter setDateFormat:@"dd MMM,yyyy HH:mm:ss"];
NSLocale * locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
dateFormatter.locale = locale;
NSString *strDate = [dateFormatter stringFromDate:date];
return strDate;
}
就会发现拿到的数据为null
解决方法:
NSLocale * locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
dateFormatter.locale = locale;
放在
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
的下面
也就是
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
UILabel * label = [[UILabel alloc] initWithFrame:CGRectMake(100, 100, [UIScreen mainScreen].bounds.size.width/2,30)];
label.textColor = [UIColor redColor];
label.text = [self timeTransfer:@"20200427130101"];
[self.view addSubview:label];
NSLog(@"timeTransfer: %@",[self timeTransfer:@"20200427130101"]);
}
-(NSString *)timeTransfer:(NSString *) string{
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
NSLocale * locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
dateFormatter.locale = locale;
[dateFormatter setDateFormat:@"yyyyMMddHHmmss"];
NSDate *date = [dateFormatter dateFromString:string];
[dateFormatter setDateFormat:@"dd MMM,yyyy HH:mm:ss"];
NSString *strDate = [dateFormatter stringFromDate:date];
return strDate;
}
鸣谢同事提醒,以及两位同仁的帮助~~~