【问题标题】:UTC time string to local time zone string.UTC 时间字符串到本地时区字符串。
【发布时间】:2015-09-16 11:41:44
【问题描述】:
我正在从服务器获取 UTC 时间,我需要根据本地时区显示这个时间,这是我的代码
NSString *UTCtime = @"10:30";
NSDateFormatter * frmt = [[NSDateFormatter alloc]init];
[frmt setDateFormat:@"HH:mm"];
NSDate *localTime = [frmt dateFromString:UTCtime];
提前谢谢你。
【问题讨论】:
标签:
ios
objective-c
nsdate
nsdateformatter
【解决方案1】:
暂时更改时区:
首先,将UTC时间字符串转换为NSDate:
NSString *UTCtime = @"10:30";
NSDateFormatter *frmt = [[NSDateFormatter alloc]init];
[frmt setDateFormat:@"HH:mm"];
[frmt setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
NSDate *utcTime = [frmt dateFromString:UTCtime];
然后计算当前时区与 UTC 的时间差(以秒为单位):
NSInteger timeZoneDiff = [[NSTimeZone systemTimeZone] secondsFromGMT];
将该时差添加到上面计算的NSDate UTC 时间
NSDate *localTime = [utcTime dateByAddingTimeInterval:timeZoneDiff];