您的位置:首页 > 其它

[iPhone/iPad] iPhone/iPad 时区转换

2011-05-27 14:57 232 查看
iPhone/iPad 时区转换
罗朝辉(http://blog.csdn.net/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;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: