【发布时间】:2014-01-04 22:10:40
【问题描述】:
我有一个应用程序,我想在其中提供 UTC 时区列表,以便用户可以选择目的地时间。我在选择器视图中有所有国家/地区的缩写。但我想要 UTC 缩写。 谁能建议我如何实现这一目标。
谢谢
【问题讨论】:
-
没有“UTC 时区”或“UTC 缩写”之类的东西。我认为您正在寻找“时区偏移”一词-与“时区”不同。请查看the timezone tag wiki。
我有一个应用程序,我想在其中提供 UTC 时区列表,以便用户可以选择目的地时间。我在选择器视图中有所有国家/地区的缩写。但我想要 UTC 缩写。 谁能建议我如何实现这一目标。
谢谢
【问题讨论】:
NSLog(@"%@", [NSTimeZone knownTimeZoneNames]);//viewDidLoad
for(id timezone in [NSTimeZone knownTimeZoneNames]){
NSLog(@"%@",[self getTimeZoneStringForAbbriviation:timezone]);
NSLog(@"%@", timezone);
}
-(NSString*)getTimeZoneStringForAbbriviation:(NSString*)abbr{
NSTimeZone *atimezone=[NSTimeZone timeZoneWithName:abbr];
int minutes = (atimezone.secondsFromGMT / 60) % 60;
int hours = atimezone.secondsFromGMT / 3600;
NSString *aStrOffset=[NSString stringWithFormat:@"%02d:%02d",hours, minutes];
return [NSString stringWithFormat:@"GMT%@",aStrOffset];
}
【讨论】:
您可以将 NSTimeZone 的 knownTimeZoneNames 属性用于所有时区。
[NSTimeZone knownTimeZoneNames]
或者您可以使用 abbreviationDictionary 获取所有缩写词
[[NSTimeZone abbreviationDictionary] allKeys]
如果你想要这些时区的时间,使用下面的代码
NSArray *abbs = [[NSTimeZone abbreviationDictionary] allKeys];
for (id eachObj in abbs) {
NSString *dateStr = [self dateFromTimeZoneAbbreviation:eachObj];
NSLog(@"%@",dateStr);
}
将方法定义为
-(NSString *)dateFromTimeZoneAbbreviation:(NSString *)abb {
NSString *dateStr;
NSTimeZone *currentTimeZone = [NSTimeZone localTimeZone];
NSTimeZone* timeZoneFromAbbreviation = [NSTimeZone timeZoneWithAbbreviation:abb];
NSInteger currentGMTOffset = [currentTimeZone secondsFromGMTForDate:[NSDate date]];
NSInteger gmtOffset = [timeZoneFromAbbreviation secondsFromGMTForDate:[NSDate date]];
NSTimeInterval gmtInterval = currentGMTOffset - gmtOffset;
NSDate *destinationDate = [[NSDate alloc] initWithTimeInterval:gmtInterval sinceDate:[NSDate date]] ;
NSDateFormatter *dateFormatters = [[NSDateFormatter alloc] init];
[dateFormatters setDateFormat:@"dd-MMM-yyyy hh:mm"];
/*[dateFormatters setDateStyle:NSDateFormatterShortStyle];
[dateFormatters setTimeStyle:NSDateFormatterShortStyle];
[dateFormatters setDoesRelativeDateFormatting:YES];*/
[dateFormatters setTimeZone:[NSTimeZone systemTimeZone]];
dateStr = [dateFormatters stringFromDate: destinationDate];
NSLog(@"DateString : %@, TimeZone : %@", dateStr , timeZoneFromAbbreviation.abbreviation);
return dateStr;
}
【讨论】: