美文网首页
iOS开发 手机当前时区与任意时区时间互转的问题

iOS开发 手机当前时区与任意时区时间互转的问题

作者: 大希爱吃鱼 | 来源:发表于2018-10-17 19:30 被阅读0次

            NSDate *date=[NSDate date];//获取时间date

            NSTimeZone* localTimeZone = [NSTimeZone localTimeZone];//获取手机当前时区

            NSIntegeroffset = [localTimeZonesecondsFromGMTForDate:date];///手机当前时区与格林威治时间的时间差

            NSTimeZone *bjTimerZone = [NSTimeZone timeZoneWithName:@"GMT+0800"];///此处以北京时区为例,可更换为GMT-0800等时区

            NSIntegerbjOffset = [bjTimerZone secondsFromGMTForDate:date];///北京时间与格林威治时间的时间差

            NSDate*localDate = [date dateByAddingTimeInterval:bjOffset - offset];///计算北京时间的date

            NSDateFormatter *format=[[NSDateFormatter alloc] init];

            [format setDateFormat:@"yyyy-MM-dd HH:mm:ss"];

            NSString*dateStr =[format stringFromDate:localDate];///拿到北京时区的时间戳

比如当前时区为东京时间2018-8-8 18:38:38,我们开发一般需要北京时间,因为存在一小时时差,那么根据上述代码就会得到正确的北京时间为 2018-8-8 17:38:38

相关文章

网友评论

      本文标题:iOS开发 手机当前时区与任意时区时间互转的问题

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