我有一个应用程序,我想在其中提供UTC时区列表,以便用户可以选择目的地时间。我有picker视图中的所有国家缩写。但我想要UTC缩写。有人能告诉我怎样才能做到这一点吗。
感谢
您可以将NSTimeZone的knownTimeZoneNames属性用于所有时区。
[NSTimeZone knownTimeZoneNames]
或者您可以使用缩写Dictionary来获取所有缩写
[[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;
}
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];
}