Date在設置系統地區爲毛里求斯的,12小時制的時候爲 NULL

吐槽:用戶反饋回這個問題的時候,我用測試機測試,沒問題,用自己的機子測試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;
}

鳴謝同事提醒,以及兩位同仁的幫助~~~

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章