【问题标题】:iOS - 3-letter Timezone abbreviation for NSTimeZoneiOS - NSTimeZone 的 3 字母时区缩写
【发布时间】:2018-07-12 21:00:47
【问题描述】:

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

[NSTimeZone abbreviationDictionary] 给出缩写为 3 个字母的代码。例如:

NSZTPDTEST

然而,

NSString * ss = [NSTimeZone timeZoneWithName:@"Pacific/Auckland"].abbreviation;

提供 GMT+12

有没有办法让我改为 NSZT/NZDT

【问题讨论】:

  • abbreviationDictionary 仅有 51 个条目,而 knownTimeZoneNames 有 437 个。如果您从这 437 个名称中的每一个创建一个 NSTimeZone 并获得 abbreviation,则只有 102 个返回一个缩写为t GMT 偏移量(其中 99 个以“America/”开头)。在没有有用缩写的 335 个中,abbreviationDictionary 中仅列出了其中的 28 个。换句话说,在 437 个时区名称中,您只能从其中的 130 个中获得有用的缩写。
  • 我需要知道非洲/内罗毕的 3 个字母缩写,任何解决方案,提前致谢。

标签: ios objective-c


【解决方案1】:

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

目标 c:

NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Pacific/Auckland"];
NSString* timeZoneName = [timeZone localizedName:NSTimeZoneNameStyleStandard
                                              locale:[NSLocale currentLocale]];
NSLog(@"%@", timeZoneName);

斯威夫特:

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:

新西兰标准时间

斯威夫特:

可选(“新西兰标准时间”)

可选(“新西兰标准时间”)

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

目标 c:

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);

斯威夫特:

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)

输出:

新西兰标准时间

【讨论】:

    【解决方案2】:

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

    NSDictionary *dict = [NSTimeZone abbreviationDictionary];
    NSArray *abbreviations = [dict allKeysForObject:@"Pacific/Auckland"];
    if (abbreviations.count > 0) {
      NSLog(@"%@", abbreviations.firstObject);
    }
    

    【讨论】:

      猜你喜欢
      • 2013-12-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-18
      • 1970-01-01
      • 2023-03-08
      • 2015-10-24
      • 1970-01-01
      相关资源
      最近更新 更多