美文网首页
UTC转本地,本地转UTC

UTC转本地,本地转UTC

作者: 小乔与周瑜 | 来源:发表于2020-09-15 00:23 被阅读0次

模拟服务器返回utc时间

    NSDate*date = [NSDate date];

    NSTimeIntervaltime =8*60*60;

    NSDate* severDate = [date dateByAddingTimeInterval:+time];

根据不同时区转换成本地时间

    NSTimeZone* sourceTimeZone = [NSTimeZone timeZoneWithAbbreviation:@"UTC"];//或GMT

    //设置转换后的目标日期时区

    NSTimeZone* destinationTimeZone = [NSTimeZone localTimeZone];

    //得到源日期与世界标准时间的偏移量

    NSInteger sourceGMTOffset = [sourceTimeZone secondsFromGMTForDate:severDate];

    //目标日期与本地时区的偏移量

    NSInteger destinationGMTOffset = [destinationTimeZone secondsFromGMTForDate:severDate];

    //得到时间偏移量的差值

    NSTime Intervalinterval =   destinationGMTOffset - sourceGMTOffset;

    NSDate* destinationDateNow = [[NSDate alloc]initWithTimeInterval :intervalsinceDate:severDate];

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

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

    NSString*str = [formatstringFromDate:destinationDateNow];

本地时间转回去服务器utc时间   interval为偏移量

[self getSeverData:str offtTime:interval];

-(void)getSeverData:(NSString*)strofftTime:(NSInteger)time{

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

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

     NSDate*date = [format dateFromString:str];

    NSDate*severDate = [date dateByAddingTimeInterval:-time];

}

相关文章

网友评论

      本文标题:UTC转本地,本地转UTC

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