How to use NSTimeZone -timeZoneWithName: with a city name from Rails ActiveSupport?

依然范特西╮ 提交于 2019-12-18 14:14:53

问题


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.


回答1:


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




回答2:


You can see list of all timezone names.

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

Hope this will be helpful for you.




回答3:


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"]]



回答4:


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"];



回答5:


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.




回答6:


NSString * TimeZoneName=[[NSTimeZone localTimeZone]name];


来源:https://stackoverflow.com/questions/10382932/how-to-use-nstimezone-timezonewithname-with-a-city-name-from-rails-activesuppo

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!