如何在iOS中获得TimeZone的三个字母缩写
[NSTimeZone abbreviationDictionary]给出了三个字母的缩写.例如:
NSZT,PDT,EST等。
然而,
NSString * ss = [NSTimeZone timeZoneWithName:@"Pacific/Auckland"].abbreviation;给出GMT+12.
有什么办法可以代替NSZT/NZDT吗?
发布于 2019-10-23 15:47:40
您可以使用以下代码获得时区的完整标准本地化名称
目标c:
NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Pacific/Auckland"];
NSString* timeZoneName = [timeZone localizedName:NSTimeZoneNameStyleStandard
locale:[NSLocale currentLocale]];
NSLog(@"%@", timeZoneName);Swift:
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:
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:
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
发布于 2018-07-13 02:28:10
正如abbreviationDictionary在评论中提到的,abbreviationDictionary只有51个条目,但是如果只使用来自abbreviationDictionary的名称,则可以使用以下代码:
NSDictionary *dict = [NSTimeZone abbreviationDictionary];
NSArray *abbreviations = [dict allKeysForObject:@"Pacific/Auckland"];
if (abbreviations.count > 0) {
NSLog(@"%@", abbreviations.firstObject);
}https://stackoverflow.com/questions/51314387
复制相似问题