Reputation: 5093
With code below, self.tzID
is set to PST
NSTimeZone *timeZone = [NSTimeZone localTimeZone];
self.tzID = [timeZone abbreviation];
I can then correctly get the TZName as America/Los_Angeles
with code:
NSDictionary *tzDict = [NSTimeZone abbreviationDictionary];
NSString *tzName = [tzDict objectForKey:self.tzID];
The problem is when he is India, tzID
is set to GMT-8 and tzDict
does not have any key GMT-8 which makes tzName
nil
.
Upvotes: 1
Views: 305
Reputation: 438082
You should be wary about using abbreviations to look up names in the dictionary. The problem is that abbreviations are ambiguous (the same abbreviation has different meanings in different places). Worse, you can't just look up what NSTimeZone
is GMT-8, because there are currently seven of them, so you have no way of knowing which the user intended.
So, you really shouldn't use abbreviations for the purposes of lookups. Use timeZone.name
(or, in Swift 3, timeZone.identifier
) not abbreviation
.
Upvotes: 0
Reputation: 299555
The way to get the name of a time zone is by asking for its localized name. For example:
NSString *name = [timeZone localizedName:NSTimeZoneNameStyleGeneric locale:nil];
This will return a correctly localized name for the time zone. Depending on what you need, you can use different styles, including "standard" and "short standard," "daylight saving," etc.
If you need to distinguish between standard and DST, use isDaylightSavingTimeForDate:
to determine which to use.
Upvotes: 1