[分享]iOS开发-NSTimeZone时区设置的使用及用时间戳来计算时间差

在项目中碰到了这个问题,当我从后台获取到时间的字符串后,我需要在前段处理“两个时间的时间差”的计算事件。当我把两段时间转换为NSDate时发现,本该是2016-04-12 14:57:58 +0000的一段时间,在转换后变成了2016-04-12 06:57:58 +0000,少了8个小时,由于中国处在东八区,也就是说这段转换后的时间属于GMT(格林尼治标准时间),所谓时区的概念就是从那里划分的,中国所采用的北京时间是GMT+8。

有了这个思路后,我开始尝试以

dateFormatter.timeZone = [NSTimeZonetimeZoneWithAbbreviation:@"GMT+0800"];

的方式来设置时区,但并没有起到效果。
随后我又尝试以添加中国标准时间名称缩写的方式,将其标准名设置为@”Asia/Shanghai”,也并没有起到效果。

在困扰中我找到了一个方法成功的解决了这个问题:

[dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:8]];//直接指定时区,这里是东8区

顺便再类举几种时区的设置方法

[NSTimeZone systemTimeZone];//系统所在时区  
[NSTimeZone defaultTimeZone];//默认时区,貌似和上一个没什么区别 
[NSTimeZone timeZoneForSecondsFromGMT:0];//这就是GMT+0时区了 

代码示例:
一个用时间戳计算两个时间的方法,代码未优化,只完成了实现,提供初步思路

        NSDateFormatter * dateFormatter1 = [[NSDateFormatter alloc] init];
        [dateFormatter1 setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
        [dateFormatter1 setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:8]];//可能需要设置时区,此处设为东8即北京时间
        NSDate * questionDate = [dateFormatter1 dateFromString:self.questionCreatetime];//时间为2016-04-12 14:48:46 +0000
        
        NSString * date2 = [MyUtil getNoneNilString:self.answerDic[@"createtime"]];
        NSDate * answerDate = [dateFormatter1 dateFromString:date2];//时间为2016-04-12 14:57:58 +0000
        
        //转换为时间戳
        NSString * timeSp1 = [NSString stringWithFormat:@"%ld", (long)[questionDate timeIntervalSince1970]];
        NSString * timeSp2 = [NSString stringWithFormat:@"%ld", (long)[answerDate timeIntervalSince1970]];
        NSInteger time1 = [timeSp1 integerValue];//1460472526
        NSInteger time2 = [timeSp2 integerValue];//1460473078
        NSInteger response = time2 - time1;//552
//        NSString * theResponse = [NSString stringWithFormat:@"%@", @(response)];//1970-01-01 00:09:12 +0000
        NSTimeInterval theResponse = response;
        NSDate * responseTimeInterval = [NSDate dateWithTimeIntervalSince1970:theResponse];
        NSDateFormatter * dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"HH:mm:ss"];
        [dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:8]];
        NSString * responseTime = [dateFormatter stringFromDate:responseTimeInterval];//输出结果00:09:12
    原文作者:ShevaKuilin
    原文地址: https://segmentfault.com/a/1190000005049256
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞