Is there any way to get TimeZone by only country n

2019-05-23 16:23发布

This question already has an answer here:

Hi I know this question is asked many times but those question relate webservice. I am developing an app that shows timezone selecting country by user. For example I have list of all the countries and when a user select one country from them I want search TimeZOne by country name (May be by string "Canada"). If i search like this is it possible to get timezone from android device? Note: My application does not use internet connection. I want to these without internet connection.

Apart from that is there any relevant way?

3条回答
Juvenile、少年°
2楼-- · 2019-05-23 17:05

The Answers to Country to Timezone mapping database address most of your Question.

If you want to avoid using the internet, then you should be able to embed one of the databases into your Android app. However, that has the obvious problem that old versions of your Android app could have (increasingly) out-of-date timezone information.

Finally, you need to be aware that some countries have multiple timezones, so you cannot determine "the timezone" solely from a country name.


Others have suggested using the TimeZone API and using the timezone ids to figure out the country name. Unfortunately, this does not work1. The timezone ids on the "Olson" database are of the form "Area/Location", where the area is "America", "Africa", etc and the location is typically a city name. The official ids do not use country names.

Wikipedia reference: TZ database : names of zones.

(Apparently, the zone.tab data does include country codes, but I don't think that is exposed in the Java / Android TimeZone API.)


1 - unless the country is Australia :-)

查看更多
我想做一个坏孩纸
3楼-- · 2019-05-23 17:17

You can do:

TimeZone tz = TimeZone.getTimeZone (id);

Where id has to be an Olson name of the form Area/Location, such as America/Los_Angeles.

You can get the available time zones using:

String[] ids = TimeZone.getAvailableIDs(0);

The official documentation: http://developer.android.com/reference/java/util/TimeZone.html

查看更多
爱情/是我丢掉的垃圾
4楼-- · 2019-05-23 17:20

If I understand your question, you could try something like this -

String[] tzIds = TimeZone.getAvailableIDs();
List<String> al = new ArrayList<String>();
for (String timeZoneId : tzIds) {
  if (timeZoneId.startsWith("Canada")) {
    al.add(timeZoneId);
  }
}
System.out.println(al);

The output (slightly re-formatted) here is

[Canada/Pacific, Canada/Yukon, Canada/Mountain, Canada/Central, 
 Canada/East-Saskatchewan, Canada/Saskatchewan, Canada/Eastern, 
 Canada/Atlantic, Canada/Newfoundland]
查看更多
登录 后发表回答