如何将时间转换为iPhone设备的时区? [英] How to convert time to the time zone of the iPhone device?
本文介绍了如何将时间转换为iPhone设备的时区?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
解决方案
//您可以使用以下函数将日期转换为希望的时区
+(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缩写ForDate:date]];
NSTimeInterval p = [myZone secondsFromGMT];
NSTimeInterval i = s-p;
NSDate * d = [NSDate dateWithTimeInterval:i sinceDate:date];
return d;
}
//测试用例**注意** cgUtil是这个方法的类,因此相应地更改它
__block NSDate * now = [NSDate date];
NSLog(@当前时间:%@,现在);
[[NSTimeZone缩写词典] allKeys] enumerateObjectsUsingBlock:^(NSString * abb,NSUInteger idx,BOOL * stop){
NSLog(@Time zone abb:%@:Time:%@,abb ,[cgUtil convertDate:now toTimeZone:abb]);
}];
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屋!
查看全文