博客> 将中国时区下的时间转成手机系统时间
将中国时区下的时间转成手机系统时间
2020-02-21 08:19 评论:0 阅读:980 奋斗的小山
ios 时区转换

NSString time = @"2017-10-08T18:40:22.161Z"; NSDateFormatter formatter = [[NSDateFormatter alloc] init]; [formatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.zzz'Z'"]; NSDate updateDate = [formatter dateFromString:time];//这样得到的date其实是虚假的UTC时区下的@"2017-10-08T18:40:22.161Z" 真正的UTC时间要慢8个小时,这也是下面减8 3600的原因。 NSTimeZone sourceTimeZone = [NSTimeZone timeZoneWithAbbreviation:@"UTC"]; NSTimeZone destinationTimeZone = [NSTimeZone localTimeZone]; NSInteger sourceGMTOffset = [sourceTimeZone secondsFromGMTForDate:updateDate] NSInteger destinationGMTOffset = [destinationTimeZone secondsFromGMTForDate:updateDate]; NSTimeInterval interval = destinationGMTOffset - sourceGMTOffset - 8 3600; //偏移8个时区; NSDate dateNow = [[NSDate alloc] initWithTimeInterval:interval sinceDate:updateDate]; [formatter setTimeZone:sourceTimeZone]; //不加这句会出现偏差,应该是跟updateDate是UTC下的时间有关 [formatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.zzz'Z'"]; NSString *localString = [formatter stringFromDate:dateNow]; NSLog(@"localString %@",localString);

收藏
0
sina weixin mail 回到顶部