首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >iOS -3- NSTimeZone的时区缩写

iOS -3- NSTimeZone的时区缩写
EN

Stack Overflow用户
提问于 2018-07-12 21:00:47
回答 2查看 743关注 0票数 1

如何在iOS中获得TimeZone的三个字母缩写

[NSTimeZone abbreviationDictionary]给出了三个字母的缩写.例如:

NSZTPDTEST等。

然而,

代码语言:javascript
复制
NSString * ss = [NSTimeZone timeZoneWithName:@"Pacific/Auckland"].abbreviation;

给出GMT+12.

有什么办法可以代替NSZT/NZDT吗?

EN

回答 2

Stack Overflow用户

发布于 2019-10-23 15:47:40

您可以使用以下代码获得时区的完整标准本地化名称

目标c:

代码语言:javascript
复制
NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Pacific/Auckland"];
NSString* timeZoneName = [timeZone localizedName:NSTimeZoneNameStyleStandard
                                              locale:[NSLocale currentLocale]];
NSLog(@"%@", timeZoneName);

Swift:

代码语言:javascript
复制
let timezone:TimeZone = TimeZone.init(identifier: "Pacific/Auckland") ?? TimeZone.current
print(timezone.localizedName(for: .generic, locale: .autoupdatingCurrent))
print(timezone.localizedName(for: .standard, locale: .autoupdatingCurrent))

输出:

目标c: 新西兰标准时间 Swift: 可选(“新西兰标准时间”) 可选(“新西兰标准时间”)

我认为现在您可以通过拆分和组合字符串从新西兰标准时间获得NZST

目标c:

代码语言:javascript
复制
NSMutableString * firstCharacters = [NSMutableString string];
NSArray *wordsArray = [timeZoneName componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
for (NSString * word in wordsArray){
 if ([word length] > 0){
    NSString * firstLetter = [word substringToIndex:1];
    [firstCharacters appendString:[firstLetter uppercaseString]];
 }
}
NSLog(@"%@", firstCharacters);

Swift:

代码语言:javascript
复制
let fullName = timezone.localizedName(for: .standard, locale: .autoupdatingCurrent) ?? ""
var result = ""
fullName.enumerateSubstrings(in: fullName.startIndex..<fullName.endIndex, options: .byWords) { (substring, _, _, _) in
    if let substring = substring { result += substring.prefix(1) }
}
print(result)

输出:

NZST

票数 1
EN

Stack Overflow用户

发布于 2018-07-13 02:28:10

正如abbreviationDictionary在评论中提到的,abbreviationDictionary只有51个条目,但是如果只使用来自abbreviationDictionary的名称,则可以使用以下代码:

代码语言:javascript
复制
NSDictionary *dict = [NSTimeZone abbreviationDictionary];
NSArray *abbreviations = [dict allKeysForObject:@"Pacific/Auckland"];
if (abbreviations.count > 0) {
  NSLog(@"%@", abbreviations.firstObject);
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51314387

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档