Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get Country Code from timezone ID in java?

Tags:

java

timezone

 String zoneId = Calendar.getInstance().getTimeZone().toZoneId();

I want to get String[] which is having the countries ISO code e.g. "AS", "AL", "AU" for which the zoneId is applicable ?

like image 991
SABER Avatar asked Jan 01 '26 13:01

SABER


1 Answers

I think the best alternative is to get these IANA's files:

  • https://github.com/eggert/tz/blob/main/zone.tab
  • https://github.com/eggert/tz/blob/main/zone1970.tab

Those files have entries in the format below:

#codes  coordinates TZ  comments
AD      +4230+00131 Europe/Andorra
AE,OM   +2518+05518 Asia/Dubai
AF      +3431+06912 Asia/Kabul

If I'm not wrong, zone1970.tab is newer and covers cases where a timezone is used by more than one country, but you can check both and see which one solves your problem.

And there's also the iso3166.tab file that maps countries codes to their respective names.

I'm not sure if Java has an API that directly reads those files, but looking at their formats, it seems to be straighforward to read them and find the info you want.


**Quick note**: there's no need to call `Calendar.getInstance().getTimeZone().toZoneId()`.

If you want your JVM's default timezone as a ZoneId object, just call ZoneId.systemDefault(). If you want the zone's ID as a String (such as Europe/Berlin or America/New_York), just call ZoneId.systemDefault().getId().

like image 138
pist Avatar answered Jan 03 '26 01:01

pist



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!