美文网首页
ios开发 解决时间戳转NSDate后,产生8小时误差

ios开发 解决时间戳转NSDate后,产生8小时误差

作者: 低音区 | 来源:发表于2023-10-12 17:54 被阅读0次

时间戳转成NSDate类型后,存在8小时误差。

原因是:

[NSDate dateWithTimeIntervalSince1970:time];

这种方式会修改解析的时区, 导致和北京时间有误差。
解决方案:

NSTimeInterval time = [currentString doubleValue];
NSDate *detaildate = [NSDate dateWithTimeIntervalSince1970:time];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat: @"yyyy-MM-dd HH:mm:ss"];
NSString*currentDateStr = [dateFormatter stringFromDate:detaildate];
NSLog(@"当前时间%@",currentDateStr);
// 当前时间2023-10-13 17:40:37
    // -- 获取当前时间戳
    NSString * currentString = [NSString stringWithFormat:@"%f",[[NSDate date] timeIntervalSince1970]];
    NSLog(@"获取当前时间戳:%@",currentString);
    // 获取当前时间戳:1697190037.687395
    
    
    // -- 时间戳直接转换日期格式
    NSTimeInterval time = [currentString doubleValue];
    NSDate *detaildate = [NSDate dateWithTimeIntervalSince1970:time];
    NSLog(@"日期格式:%@",detaildate);
    // 日期格式:2023-10-13 09:40:37 +0000
    
    
    // -- 格式话后的日期
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat: @"yyyy-MM-dd HH:mm:ss"];
    NSString*currentDateStr = [dateFormatter stringFromDate:detaildate];
    NSLog(@"当前时间%@",currentDateStr);
    // 当前时间2023-10-13 17:40:37
    
    
    // -- 
    NSDate * changeDate = [dateFormatter dateFromString:currentDateStr];
    NSLog(@"转换完成后时间格式:%@",currentDateStr);
    // 转换完成后时间格式:2023-10-13 17:40:37

相关文章

网友评论

      本文标题:ios开发 解决时间戳转NSDate后,产生8小时误差

      本文链接:https://www.haomeiwen.com/subject/ecdobdtx.html