iOS新手学习

iOS时间转换 真机和模拟器错误 输出为空的解决方案

2016-12-31  本文已影响425人  Melody_YM

iphone中NSDateFormatter模拟器可以正常显示,但在真机上不行,转换后的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转NSString
-(NSString *)stringFromDate:(NSDate *)date
{
    NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setLocale:locale];
    //设置格式:zzz表示时区
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    //NSDate转NSString
    NSString *currentDateString = [dateFormatter stringFromDate:date];
    //输出currentDateString
    NSLog(@"%@",currentDateString);
    return currentDateString;
}

//NSString转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转NSDate
    NSDate *date=[formatter dateFromString:string];
    return date;
}

找了半天,终于找到原因:
在真机运行需要设置Local,添加下面一段代码就OK:

NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
[formatter setLocale:locale];
上一篇下一篇

猜你喜欢

热点阅读