美文网首页
iOS GMT 时间的转换(Mon Nov 05 2018 03

iOS GMT 时间的转换(Mon Nov 05 2018 03

作者: abcdef沧海 | 来源:发表于2018-11-09 09:40 被阅读19次

由于我们后端给返回的时间格式是GMT 格式,需要我们前端对格式进行转换,我查了好多资料iOS都没有相关的方法,最后自己写的。然后自己对MGT UTC 时间格式转换做了下总结,希望能对以后遇到问题的同行有所帮助。

  1. MGT 时间 转本地时间格式

我们后端返回的GMT 格式

Mon Nov 05 2018 03:37:51 GMT+0000 (Coordinated Universal Time)

----> 2018/11/5 11:37:51

附上代码

+(NSString *)convertGMTtoLocalTimeConversion:(NSString *)gmtDateStr
{
NSDateFormatter * formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"EEE MMM dd yyyy HH:mm:ss 'GMT'Z' (Coordinated Universal Time)'"];

NSTimeZone * local = [NSTimeZone systemTimeZone];
[formatter setTimeZone:local];
[formatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]];
NSDate * localDate = [formatter dateFromString:gmtDateStr]; 
NSTimeInterval localTimeInterval = [localDate timeIntervalSinceReferenceDate];
NSDate * localCurrentDate = [NSDate dateWithTimeIntervalSinceReferenceDate:localTimeInterval];
[formatter setDateFormat:@"yyyy/MM/dd HH:mm:ss"];
NSString *dateString = [formatter stringFromDate:localCurrentDate];
 
// NSLog(@"时间-localCurrentDate----dateString--:%@ %@",localCurrentDate,dateString);

return dateString;

}

2.iOS生成GMT时间 方法
/**
2018-11-09 09:38:39 -> Sun, 09 Nov 2018 01:38:39 GMT
*/
NSDate *date = [NSDate date];
NSTimeZone *tzGMT = [NSTimeZone timeZoneWithName:@"GMT"];
[NSTimeZone setDefaultTimeZone:tzGMT];
NSDateFormatter *iosDateFormater=[[NSDateFormatter alloc]init];
iosDateFormater.dateFormat=@"EEE, d MMM yyyy HH:mm:ss 'GMT'";
iosDateFormater.locale=[[NSLocale alloc]initWithLocaleIdentifier:@"en_US"];
NSString *dateStr = [iosDateFormater stringFromDate:date];

输出结果为 Sun, 09 Nov 2018 01:38:39 GMT

  1. UTC 时间转本地时间
    /**
    2018-11-09 09:38:39 -> 2018/11/09 09:38:39
    */
  • (NSString *)getLocalDateFormateUTCDate:(NSString *)utcStr { NSDateFormatter *format = [[NSDateFormatter alloc] init];
    format.dateFormat = @"yyyy/MM/dd HH:mm:ss";
    format.timeZone = [NSTimeZone timeZoneWithName:@"UTC"];
    NSDate *utcDate = [format dateFromString:utcStr];
    format.timeZone = [NSTimeZone localTimeZone];
    NSString *dateString = [format stringFromDate:utcDate];
    return dateString;
    }

相关文章

网友评论

      本文标题:iOS GMT 时间的转换(Mon Nov 05 2018 03

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