如何将时间转换为 iPhone 设备的时区? [英] How to convert time to the time zone of the iPhone device?
本文介绍了如何将时间转换为 iPhone 设备的时区?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在 EST 时区有一个时间,它是使用 mysql 服务器上的 NOW() 函数完成的.因为我的服务器在EST,所以存储的时间是在EST.当我从 iPhone 上的应用程序检索它时,我需要在用户的正确时区中显示它.我该怎么做?
I have a time in EST timezone, it is done using the NOW() function on the mysql server. Because my server is located in EST, the time stored is in EST. When I retrieve it from my app on the iPhone, I need to display it in the correct time zone of the user. How do I do that?
推荐答案
//您可以使用以下函数将日期转换为您希望的时区
//You can use the below function to convert date to a time zone you wish
+ (NSDate *) convertDate:(NSDate *) date toTimeZone:(NSString *) timeZoneAbbreviation {
NSTimeZone *systemZone = [NSTimeZone systemTimeZone];
NSTimeZone *zoneUTC = [NSTimeZone timeZoneWithAbbreviation:timeZoneAbbreviation];
NSTimeInterval s = [zoneUTC secondsFromGMT];
NSTimeZone *myZone = [NSTimeZone timeZoneWithAbbreviation:[systemZone abbreviationForDate:date]];
NSTimeInterval p = [myZone secondsFromGMT];
NSTimeInterval i = s-p;
NSDate *d = [NSDate dateWithTimeInterval:i sinceDate:date];
return d;
}
//Test case **note** cgUtil is the class this method is written thus change it accordingly
__block NSDate *now = [NSDate date];
NSLog(@"Current time:%@", now);
[[[NSTimeZone abbreviationDictionary] allKeys] enumerateObjectsUsingBlock:^(NSString * abb, NSUInteger idx, BOOL *stop) {
NSLog(@"Time zone abb:%@:Time:%@",abb,[cgUtil convertDate:now toTimeZone:abb]);
}];
这篇关于如何将时间转换为 iPhone 设备的时区?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文