[Cocoa] iPhone/iPad 时区转换

iPhone/iPad 时区转换

罗朝辉 (http://www.cnblogs.com/kesalin/)

本文遵循“署名-非商业用途-保持一致”创作公用协议

在服务器使用的时区与用户本地时区不一致的情况下,如果需要显示从服务器得来的时间,我们需要进行必要的时区和显示格式转换。

其转换过程为:

获取源(服务器)NSDateFormatter,用这 NSDateFormatter 得 dateFromString 方法获得源时区的时间。

然后计算两个时区的时间偏差量,用这个偏差量加上前面计算得到的源时区时间就得到用户本地时区的时间了。

参见代码:

参数 srcFormat:是源时区时间的显示格式

参数 dstFormat:是本地时区时间的显示格式

- (NSString *)localeTimeZoneTimeWithSrcFormat:(NSString *)srcFormat dstFormat: (NSString *) dstFormat

{

NSDateFormatter *usFormatter = [[[NSDateFormatter alloc] init] autorelease];

usFormatter.locale = [[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"] autorelease];

[usFormatter setDateFormat:srcFormat];

NSDate *srcDate = [usFormatter dateFromString:self];



NSTimeZone *srcTimeZone = [NSTimeZone timeZoneWithAbbreviation:@"EST"]; // America/New_York

NSTimeZone *dstTimeZone = [NSTimeZone localTimeZone];

NSInteger srcGMTOffset = [srcTimeZone secondsFromGMTForDate:srcDate];

NSInteger dstGMTOffset = [dstTimeZone secondsFromGMTForDate:srcDate];

NSTimeInterval interval = dstGMTOffset - srcGMTOffset;

NSDate *dstDate = [[[NSDate alloc] initWithTimeInterval:interval sinceDate:srcDate] autorelease];



NSDateFormatter *localeFormatter = [NSString localeDateFormatterInstance];

[localeFormatter setDateFormat:dstFormat];

NSString *formattedDateString = [localeFormatter stringFromDate:dstDate];



return formattedDateString;

}



原文地址:https://www.cnblogs.com/kesalin/p/time_zone_convert.html