Question

If I only have the city name like Bangkok or Tokyo, how can I supply a timezone parameter in [NSTimeZone timeZoneWithName:@"Asia/Tokyo"] where it also has continent and slash in front of city?

I already tried [NSTimeZone timeZoneWithName:@"Tokyo"], it doesn't work.

Was it helpful?

Solution

Thanks for the answers guys, but it looks like those city names are just a format that Rails "ActiveSupport::TimeZone" uses. So I just have to map it back. The mapping is here -> http://api.rubyonrails.org/classes/ActiveSupport/TimeZone.html

It maps the timezone from Rails "ActiveSupport::TimeZone" format to another format that iOS uses (e.g. "International Date Line West" => "Pacific/Midway", "Midway Island" => "Pacific/Midway", "Samoa" => "Pacific/Pago_Pago", ... ).

I have created a plist file containing a NSDictionary property that can easily be used for mapping.

Edit: an updated version (with usage example) for Rails 3.2 (thanks RJ Regenold!)

OTHER TIPS

You can see list of all timezone names.

NSLog(@"%@", [NSTimeZone knownTimeZoneNames]);

Hope this will be helpful for you.

If they're all in Asia, why not use something like:

MYCITY=Tokyo
[NSTimeZone timeZoneWithName:@"Asia/$MYCITY"]

If you need more cities and timezones, you could create a static text list file based on all the time zones found at /usr/share/zoneinfo.

create file 'timezones.by.city.txt' with the following text. (Truncated here.)

"Asia/Aden"
"Asia/Almaty"
"Asia/Amman"
"Asia/Anadyr"
"Asia/Aqtau"
"Asia/Aqtobe"
"Asia/Ashgabat"
"Asia/Ashkhabad"
"Asia/Baghdad"
"Asia/Bahrain"
"Asia/Baku"
"Asia/Bangkok"
"Asia/Beirut"
"Asia/Bishkek"
... etc.
"US/Alaska"
"US/Aleutian"
"US/Arizona"
"US/Central"
"US/Eastern"
"US/East-Indiana"
"US/Hawaii"
"US/Indiana-Starke"
"US/Michigan"
"US/Mountain"
"US/Pacific"
"US/Pacific-New"
"US/Samoa"

Then:

MYCITY=Bangkok
MYTZ=`grep "$MYCITY" ./timezones.by.city.txt`
[df setTimeZone:[NSTimeZone timeZoneWithName:@"$MYTZ"]]
NSArray *zones = [NSTimeZone knownTimeZoneNames];

It returns all the set of timeszones supported by your system.

You have to setTime zone like below, which you have tried already.

[NSTimeZone timeZoneWithName:@"Asia/Tokyo"];

You may find the dataset and/or API from http://www.geonames.org/ useful in solving this sort of problem. They have the correct olsen timezone (which is what the 'Asia/Tokyo' is called) for a vast number of locations and you can either download and wrangle the data yourself, or use their API to get what you need.

NSString * TimeZoneName=[[NSTimeZone localTimeZone]name];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top