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

拜拜、爱过 提交于 2019-11-30 11:09:24

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

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

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