The builtin Java classes don't offer this, but ICU's TimeZone class does, and TimeZone.getAvailableIDs("US") provides the correct answer.

Answer from arnt on Stack Overflow
🌐
Stack Overflow
stackoverflow.com › questions › 58396750
Need timezone based on the ISO country code and city in Java - Stack Overflow
Rough way I found to achieve is - private static String getSourceLocalTimeZone(String countryCode, String city, String sourceLocalTimeZone) { String[] timeZones = com.ibm.icu.util.TimeZone.getAvailableIDs(countryCode); for (String timeZone : timeZones) { String cityFromTimeZone = null; String[] value = timeZone.split("/"); if (value != null && value.length > 0) { cityFromTimeZone = value[value.length - 1].replace("_", " "); } if (city!=null && city.matches("(.*)" + cityFromTimeZone + "(.*)")) { sourceLocalTimeZone = timeZone; break; } } if (sourceLocalTimeZone == null || (sourceLocalTimeZone.isEmpty())) { if(timeZones.length>0) sourceLocalTimeZone = timeZones[0]; } return sourceLocalTimeZone; } Dependency - <dependency> <groupId>com.ibm.icu</groupId> <artifactId>icu4j</artifactId> <version>4.6</version> </dependency>
🌐
DZone
dzone.com › coding › java › how to get a country’s time zone in java
How to Get a Country’s Time Zone in Java
February 17, 2021 - Country Code or Name — the country code or name for your target country.
🌐
Coderanch
coderanch.com › t › 469915 › java › Solution-displaying-time-inputting-country
Solution for displaying time by inputting country code (Beginning Java forum at Coderanch)
November 6, 2009 - Hi, All you need is: - current time - list of all available TimeZones ( String[] TimeZone.getAvailableIDs() ) - call in a loop df.setTimeZone(timezone[idx]) and print it out to the console This should work. Regarding the Locale. This is just a visual presentation of the time and nothing else (no GMT+/- or DST). Regards, Rok ... thanks. but i need to input the standard iso country code and then display the time accordingly.
🌐
Codereye
codereye.com › 2009 › 07 › getting-all-time-zones-of-country.html
Getting all time zones of a Country in Java - Coder Eye
July 18, 2009 - String[] timeZones = com.ibm.icu.util.TimeZone.getAvailableIDs(countryCode); This example will return all the available time zones in Israel. Note that the input to this function is country code. If we had a locale we could have written: String[] timeZones = com.ibm.icu.util.TimeZone.getAv...
🌐
Objects
helpdesk.objects.com.au › home › java
Can I find all available timezones for a country? | web development helpdesk
January 8, 2023 - The ICU4J package provides a method for returning the available timezones for a given country code. The following code will return a Map containing all available TimeZone's for each country, keyed on country code. [sourcecode lang="java"] public static Map getAvailableTimeZones() { Map ...
🌐
Coderanch
coderanch.com › t › 583127 › java › Timezone-City-State-Province-Country
To know Timezone given City,State/Province,Country (Java in General forum at Coderanch)
Hi Maulin, If you look at the getTimeZone() method of the Calendar class clearly you can see there is a way to get a TimeZone from a given Calendar. The trick is to get an appropriate calendar instance using the getInstance() method of Calendar, passing in a Locale. Unfortunately that'll not help down to the city level. The above will only work for countries.
🌐
Unicode
unicode-org.github.io › icu-docs › apidoc › dev › icu4j › com › ibm › icu › util › TimeZone.html
TimeZone (ICU4J 78)
region - The ISO 3166 two-letter country code or UN M.49 three-digit area code. When null, no filtering done by region. rawOffset - An offset from GMT in milliseconds, ignoring the effect of daylight savings time, if any. When null, no filtering done by zone offset. ... Stable ICU 4.8. public static String[] getAvailableIDs​(int rawOffset) Return a new String array containing all system TimeZone IDs with the given raw offset from GMT. These IDs may be passed to get() to construct the corresponding TimeZone object.
Find elsewhere
🌐
Stack Overflow
stackoverflow.com › questions › 14135355 › get-timezone-by-country-region-in-java
Get TimeZone by Country/Region in Java - Stack Overflow
You cannot get a timezone from the http request directly as mentioned here: Is there another way to get a user's time zone from a HttpServletRequest object in Spring MVC? But you can determine it by ip address. Mentioned here: How to programmatically find geo location of incoming http request? You can also use getTimeZoneOffset(). Mentioned here: User needs to display transaction in there local time as they login from different country.
🌐
CodingTechRoom
codingtechroom.com › question › -get-timezone-java-country-code
How to Retrieve the Time Zone of a Location Using Country Code in Java - CodingTechRoom
To retrieve the time zone of a specific area using its country code in Java, you can utilize the `java.time` package, specifically leveraging `ZoneId` and `ZonedDateTime` classes.
Top answer
1 of 4
6

tl;dr

ZonedDateTime.now(                          // Capture the current moment as seen by the wall-clock time used by the people of a certain region (a time zone).
    ZoneId.of( "Europe/Paris" )             // Specify time zone by official IANA time zone name.  https://en.wikipedia.org/wiki/Tz_database
)                                           // Returns a `ZonedDateTime` object.
.withZoneSameInstant(                       // Adjust from Paris time to Auckland time, just to show that we can. Same moment, different wall-clock time.
    ZoneId.of( "Pacific/Auckland" )
)                                           // Returns a new, second `ZonedDateTime` object without changing (“mutating”) the first. Per immutable objects pattern.
.format(                                    // Generate a String representing the value of our `ZonedDateTime`.
    DateTimeFormatter.ofLocalizedDateTime(  // Let java.time automatically localize.
        FormatStyle.FULL                    // Specify the length/abbreviation of new String.
    )                                       // Returns a `DateTimeFormatter` using the JVM’s current default `Locale`. Override this default in next line.
    .withLocale( Locale.ITALIAN )           // Locale is unrelated to time zone. Wall-clock time of Auckland, presented in Italian – perfectly reasonable depending on the needs of your user.
)                                           // Returns a String object holding text that represents the value of our `ZonedDateTime` object.

domenica 8 aprile 2018 08:48:16 Ora standard della Nuova Zelanda

Country does not determine time zone

Current date and time on the basis of country code

No can do.

There is no direct link between country and time zone.

Geographically large countries often straddle multiple time zones, so that the wall-clock time of each region keeps close to solar time (meaning “noon” is when the sun is overhead). Present-day India is unusual in using one time zone across its vast land mass.

Also, there are often enclaves within a country that use a different time zone. This is often related to joining or refusing Daylight Saving Time (DST). For example, in the United States the state of Arizona opts out of the silliness of DST. Yet within Arizona is part of the Navajo Nation which does participate in DST. So neither country nor state/province determines time zone.

Furthermore, there is more to think about than the current offset-from-UTC. A time zone is a history of past, present, and future changes to the offset used by the people of a region. Cutovers in Daylight Saving Time (DST) is one common cause of the offset changing in a zone. Determining earlier/later moments requires a time zone to apply these historical adjustments.

So forget about countries. Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter pseudo-zones such as EST or IST as they are not true time zones, not standardized, and not even unique(!).

ZoneId z = ZoneId.of( "Africa/Tunis" ) ;

Country code as a hint

You could guess, or present a short list for the user to choose from, based on their current geolocation or country code. See the Answer by well on this page for a data file listing the approximately 350 time zones in use since 1970 along with their longitude/latitude and country code.

Excerpt:

…
TK  -0922-17114 Pacific/Fakaofo
TL  -0833+12535 Asia/Dili
TM  +3757+05823 Asia/Ashgabat
TN  +3648+01011 Africa/Tunis
TO  -2110-17510 Pacific/Tongatapu
TR  +4101+02858 Europe/Istanbul
…

Locale & time zone are orthogonal issues

i tried setting locale of specified country as well but i am getting same output ?

Locale has nothing to do with time zone & offset-from-UTC. Locale determines the human language and cultural norms used in localization when generating strings to represent the date-time value. So locale does not affect the meaning.

To localize, specify:

  • FormatStyle to determine how long or abbreviated should the string be.
  • Locale to determine (a) the human language for translation of name of day, name of month, and such, and (b) the cultural norms deciding issues of abbreviation, capitalization, punctuation, separators, and such.

For example, consider an engineer from Québec attending a conference in India. She will want to view the conference schedule using the Asia/Kolkata time zone to match the time-of-day seen on the clocks on the walls.

LocalDate ld = LocalDate.of( 2018 , Month.JANUARY , 23 ) ;
LocalTime lt =LocalTime.of( 14 , 0 ) ;
ZoneId z = ZoneId.of( "Asia/Kolkata" ) ;
ZonedDateTime zdt = ZonedDateTime.of( ld , lt , z ) ;  // Conference session start. 

2018-01-23T14:00+05:30[Asia/Kolkata]

But our engineer would prefer to read the text and formatting in her native French, Locale.CANADA_FRENCH.

Locale locale = Locale.CANADA_FRENCH;
DateTimeFormatter f = DateTimeFormatter.ofLocalizedDateTime( FormatStyle.FULL ).withLocale( locale );
String output = zdt.format( f );

mardi 23 janvier 2018 à 14:00:00 India Standard Time

Other time zones

My requirement is to get the current date and time of on the basis of country code like (DE, IT ,ES, IE , PT ,UK)

You can make a new ZonedDateTime using a different time zone but with the same moment (Instant) inside. So you will see a different wall-clock time, yet continue to refer to the same moment, same point on the timeline.

ZoneId zMadrid = ZoneId.of( "Europe/Madrid" ) ;
ZonedDateTime zdtMadrid = zdt.withZoneSameInstant( zMadrid) ;  // Same moment, different wall-clock time.

zdtMadrid.toString(): 2018-01-23T09:30+01:00[Europe/Madrid]

Perhaps localize that Spain-zoned moment in Japanese.

DateTimeFormatter fJapan = DateTimeFormatter.ofLocalizedDateTime( FormatStyle.FULL ).withLocale( Locale.JAPAN );
String outputJapan = zdtMadrid.format( fJapan );  // Zone & locale are unrelated, orthogonal issues.
System.out.println(outputJapan);

So we get a Madrid time presented in Japanese language/culture.

2018年1月23日火曜日 9時30分00秒 中央ヨーロッパ標準時

UTC

Generally speaking, you should use UTC values for much of you business logic, logging, storage, and exchange. Simply extract a Instant from our ZonedDateTime. Both the Instant and ZonedDateTime represent the same moment, the same point on the timeline, but viewed using a different wall-clock time.

Instant instant = zdt.toInstant() ;  // Capture current moment in UTC.

Going the other direction:

ZonedDateTime zdt = instant.atZone( "Europe/Helsinki" ) ;  // Same simultaneous moment, different wall-clock time.

Avoid legacy classes

The troublesome old date-time classes were supplanted years ago by the java.time classes. Instead of Calendar use ZonedDateTime.

ZoneId z = ZoneId.of( "Pacific/Auckland" ) ;
ZonedDateTime zdt = ZonedDateTime.now( z ) ;

For a moment in UTC, Use Instant. The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).

Instant instant = Instant.now() ;

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes. Hibernate 5 & JPA 2.2 support java.time.

Where to obtain the java.time classes?

  • Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.
    • Java 9 brought some minor features and fixes.
  • Java SE 6 and Java SE 7
    • Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
  • Android
    • Later versions of Android (26+) bundle implementations of the java.time classes.
    • For earlier Android (<26), the process of API desugaring brings a subset of the java.time functionality not originally built into Android.
      • If the desugaring does not offer what you need, the ThreeTenABP project adapts ThreeTen-Backport (mentioned above) to Android. See How to use ThreeTenABP….
2 of 4
2

I created a table that maps a user's country code to a timezone. If a country has several time zones then the closest time zone to Greenwich Mean Time Zone is taken into account in the table. It's not perfect but it deserves to work.

function country_to_timezone($country_code)
{
    $country_code = mb_strtoupper($country_code);

    $timezone_list = array('AD' => 'Europe/Andorra',
                                'AE' => 'Asia/Dubai',
                                'AF' => 'Asia/Kabul',
                                'AG' => 'America/Antigua',
                                'AI' => 'America/Anguilla',
                                'AL' => 'Europe/Tirane',
                                'AM' => 'Asia/Yerevan',
                                'AO' => 'Africa/Luanda',
                                'AQ' => 'Antarctica/McMurdo',
                                'AR' => 'America/Argentina/Buenos_Aires',
                                'AS' => 'Pacific/Pago_Pago',
                                'AT' => 'Europe/Vienna',
                                'AU' => 'Australia/Lord_Howe',
                                'AW' => 'America/Aruba',
                                'AX' => 'Europe/Mariehamn',
                                'AZ' => 'Asia/Baku',
                                'BA' => 'Europe/Sarajevo',
                                'BB' => 'America/Barbados',
                                'BD' => 'Asia/Dhaka',
                                'BE' => 'Europe/Brussels',
                                'BF' => 'Africa/Ouagadougou',
                                'BG' => 'Europe/Sofia',
                                'BH' => 'Asia/Bahrain',
                                'BI' => 'Africa/Bujumbura',
                                'BJ' => 'Africa/Porto-Novo',
                                'BL' => 'America/St_Barthelemy',
                                'BM' => 'Atlantic/Bermuda',
                                'BN' => 'Asia/Brunei',
                                'BO' => 'America/La_Paz',
                                'BQ' => 'America/Kralendijk',
                                'BR' => 'America/Noronha',
                                'BS' => 'America/Nassau',
                                'BT' => 'Asia/Thimphu',
                                'BW' => 'Africa/Gaborone',
                                'BY' => 'Europe/Minsk',
                                'BZ' => 'America/Belize',
                                'CA' => 'America/St_Johns',
                                'CC' => 'Indian/Cocos',
                                'CD' => 'Africa/Kinshasa',
                                'CF' => 'Africa/Bangui',
                                'CG' => 'Africa/Brazzaville',
                                'CH' => 'Europe/Zurich',
                                'CI' => 'Africa/Abidjan',
                                'CK' => 'Pacific/Rarotonga',
                                'CL' => 'America/Santiago',
                                'CM' => 'Africa/Douala',
                                'CN' => 'Asia/Shanghai',
                                'CO' => 'America/Bogota',
                                'CR' => 'America/Costa_Rica',
                                'CU' => 'America/Havana',
                                'CV' => 'Atlantic/Cape_Verde',
                                'CW' => 'America/Curacao',
                                'CX' => 'Indian/Christmas',
                                'CY' => 'Asia/Nicosia',
                                'CZ' => 'Europe/Prague',
                                'DE' => 'Europe/Berlin',
                                'DJ' => 'Africa/Djibouti',
                                'DK' => 'Europe/Copenhagen',
                                'DM' => 'America/Dominica',
                                'DO' => 'America/Santo_Domingo',
                                'DZ' => 'Africa/Algiers',
                                'EC' => 'America/Guayaquil',
                                'EE' => 'Europe/Tallinn',
                                'EG' => 'Africa/Cairo',
                                'EH' => 'Africa/El_Aaiun',
                                'ER' => 'Africa/Asmara',
                                'ES' => 'Europe/Madrid',
                                'ET' => 'Africa/Addis_Ababa',
                                'FI' => 'Europe/Helsinki',
                                'FJ' => 'Pacific/Fiji',
                                'FK' => 'Atlantic/Stanley',
                                'FM' => 'Pacific/Chuuk',
                                'FO' => 'Atlantic/Faroe',
                                'FR' => 'Europe/Paris',
                                'GA' => 'Africa/Libreville',
                                'GB' => 'Europe/London',
                                'GD' => 'America/Grenada',
                                'GE' => 'Asia/Tbilisi',
                                'GF' => 'America/Cayenne',
                                'GG' => 'Europe/Guernsey',
                                'GH' => 'Africa/Accra',
                                'GI' => 'Europe/Gibraltar',
                                'GL' => 'America/Nuuk',
                                'GM' => 'Africa/Banjul',
                                'GN' => 'Africa/Conakry',
                                'GP' => 'America/Guadeloupe',
                                'GQ' => 'Africa/Malabo',
                                'GR' => 'Europe/Athens',
                                'GS' => 'Atlantic/South_Georgia',
                                'GT' => 'America/Guatemala',
                                'GU' => 'Pacific/Guam',
                                'GW' => 'Africa/Bissau',
                                'GY' => 'America/Guyana',
                                'HK' => 'Asia/Hong_Kong',
                                'HN' => 'America/Tegucigalpa',
                                'HR' => 'Europe/Zagreb',
                                'HT' => 'America/Port-au-Prince',
                                'HU' => 'Europe/Budapest',
                                'ID' => 'Asia/Jakarta',
                                'IE' => 'Europe/Dublin',
                                'IL' => 'Asia/Jerusalem',
                                'IM' => 'Europe/Isle_of_Man',
                                'IN' => 'Asia/Kolkata',
                                'IO' => 'Indian/Chagos',
                                'IQ' => 'Asia/Baghdad',
                                'IR' => 'Asia/Tehran',
                                'IS' => 'Atlantic/Reykjavik',
                                'IT' => 'Europe/Rome',
                                'JE' => 'Europe/Jersey',
                                'JM' => 'America/Jamaica',
                                'JO' => 'Asia/Amman',
                                'JP' => 'Asia/Tokyo',
                                'KE' => 'Africa/Nairobi',
                                'KG' => 'Asia/Bishkek',
                                'KH' => 'Asia/Phnom_Penh',
                                'KI' => 'Pacific/Tarawa',
                                'KM' => 'Indian/Comoro',
                                'KN' => 'America/St_Kitts',
                                'KP' => 'Asia/Pyongyang',
                                'KR' => 'Asia/Seoul',
                                'KW' => 'Asia/Kuwait',
                                'KY' => 'America/Cayman',
                                'KZ' => 'Asia/Almaty',
                                'LA' => 'Asia/Vientiane',
                                'LB' => 'Asia/Beirut',
                                'LC' => 'America/St_Lucia',
                                'LI' => 'Europe/Vaduz',
                                'LK' => 'Asia/Colombo',
                                'LR' => 'Africa/Monrovia',
                                'LS' => 'Africa/Maseru',
                                'LT' => 'Europe/Vilnius',
                                'LU' => 'Europe/Luxembourg',
                                'LV' => 'Europe/Riga',
                                'LY' => 'Africa/Tripoli',
                                'MA' => 'Africa/Casablanca',
                                'MC' => 'Europe/Monaco',
                                'MD' => 'Europe/Chisinau',
                                'ME' => 'Europe/Podgorica',
                                'MF' => 'America/Marigot',
                                'MG' => 'Indian/Antananarivo',
                                'MH' => 'Pacific/Majuro',
                                'MK' => 'Europe/Skopje',
                                'ML' => 'Africa/Bamako',
                                'MM' => 'Asia/Yangon',
                                'MN' => 'Asia/Ulaanbaatar',
                                'MO' => 'Asia/Macau',
                                'MP' => 'Pacific/Saipan',
                                'MQ' => 'America/Martinique',
                                'MR' => 'Africa/Nouakchott',
                                'MS' => 'America/Montserrat',
                                'MT' => 'Europe/Malta',
                                'MU' => 'Indian/Mauritius',
                                'MV' => 'Indian/Maldives',
                                'MW' => 'Africa/Blantyre',
                                'MX' => 'America/Mexico_City',
                                'MY' => 'Asia/Kuala_Lumpur',
                                'MZ' => 'Africa/Maputo',
                                'NA' => 'Africa/Windhoek',
                                'NC' => 'Pacific/Noumea',
                                'NE' => 'Africa/Niamey',
                                'NF' => 'Pacific/Norfolk',
                                'NG' => 'Africa/Lagos',
                                'NI' => 'America/Managua',
                                'NL' => 'Europe/Amsterdam',
                                'NO' => 'Europe/Oslo',
                                'NP' => 'Asia/Kathmandu',
                                'NR' => 'Pacific/Nauru',
                                'NU' => 'Pacific/Niue',
                                'NZ' => 'Pacific/Auckland',
                                'OM' => 'Asia/Muscat',
                                'PA' => 'America/Panama',
                                'PE' => 'America/Lima',
                                'PF' => 'Pacific/Tahiti',
                                'PG' => 'Pacific/Port_Moresby',
                                'PH' => 'Asia/Manila',
                                'PK' => 'Asia/Karachi',
                                'PL' => 'Europe/Warsaw',
                                'PM' => 'America/Miquelon',
                                'PN' => 'Pacific/Pitcairn',
                                'PR' => 'America/Puerto_Rico',
                                'PS' => 'Asia/Gaza',
                                'PT' => 'Europe/Lisbon',
                                'PW' => 'Pacific/Palau',
                                'PY' => 'America/Asuncion',
                                'QA' => 'Asia/Qatar',
                                'RE' => 'Indian/Reunion',
                                'RO' => 'Europe/Bucharest',
                                'RS' => 'Europe/Belgrade',
                                'RU' => 'Europe/Kaliningrad',
                                'UA' => 'Europe/Simferopol',
                                'RW' => 'Africa/Kigali',
                                'SA' => 'Asia/Riyadh',
                                'SB' => 'Pacific/Guadalcanal',
                                'SC' => 'Indian/Mahe',
                                'SD' => 'Africa/Khartoum',
                                'SE' => 'Europe/Stockholm',
                                'SG' => 'Asia/Singapore',
                                'SH' => 'Atlantic/St_Helena',
                                'SI' => 'Europe/Ljubljana',
                                'SJ' => 'Arctic/Longyearbyen',
                                'SK' => 'Europe/Bratislava',
                                'SL' => 'Africa/Freetown',
                                'SM' => 'Europe/San_Marino',
                                'SN' => 'Africa/Dakar',
                                'SO' => 'Africa/Mogadishu',
                                'SR' => 'America/Paramaribo',
                                'SS' => 'Africa/Juba',
                                'ST' => 'Africa/Sao_Tome',
                                'SV' => 'America/El_Salvador',
                                'SX' => 'America/Lower_Princes',
                                'SY' => 'Asia/Damascus',
                                'SZ' => 'Africa/Mbabane',
                                'TC' => 'America/Grand_Turk',
                                'TD' => 'Africa/Ndjamena',
                                'TF' => 'Indian/Kerguelen',
                                'TG' => 'Africa/Lome',
                                'TH' => 'Asia/Bangkok',
                                'TJ' => 'Asia/Dushanbe',
                                'TK' => 'Pacific/Fakaofo',
                                'TL' => 'Asia/Dili',
                                'TM' => 'Asia/Ashgabat',
                                'TN' => 'Africa/Tunis',
                                'TO' => 'Pacific/Tongatapu',
                                'TR' => 'Europe/Istanbul',
                                'TT' => 'America/Port_of_Spain',
                                'TV' => 'Pacific/Funafuti',
                                'TW' => 'Asia/Taipei',
                                'TZ' => 'Africa/Dar_es_Salaam',
                                'UG' => 'Africa/Kampala',
                                'UM' => 'Pacific/Midway',
                                'US' => 'America/New_York',
                                'UY' => 'America/Montevideo',
                                'UZ' => 'Asia/Samarkand',
                                'VA' => 'Europe/Vatican',
                                'VC' => 'America/St_Vincent',
                                'VE' => 'America/Caracas',
                                'VG' => 'America/Tortola',
                                'VI' => 'America/St_Thomas',
                                'VN' => 'Asia/Ho_Chi_Minh',
                                'VU' => 'Pacific/Efate',
                                'WF' => 'Pacific/Wallis',
                                'WS' => 'Pacific/Apia',
                                'YE' => 'Asia/Aden',
                                'YT' => 'Indian/Mayotte',
                                'ZA' => 'Africa/Johannesburg',
                                'ZM' => 'Africa/Lusaka',
                                'ZW' => 'Africa/Harare'
                                );

    if (!$timezone_list[$country_code]) {
        return $country_code;
    } else {
        return $timezone_list[$country_code];
    }
}
🌐
SAP Community
answers.sap.com › questions › 7368553 › get-time-zone-based-on-country-code.html
Solved: Get time Zone based on Country code - SAP Community
May 26, 2010 - Subscribe to RSS Feed · Permalink · Print · Report Inappropriate Content · ‎2010 May 26 12:47 PM · 0 Likes · > I am looking for getting the time and date of a particular country based on country code in XI. How should that work? Have you thought about Russia? USA? Check java class Calendar and TimeZone: http://java.sun.com/j2se/1.5.0/docs/api/java/util/Calendar.html ·
Top answer
1 of 1
5

For a solution covering all thinkable city names this will require a database containing cities and their corresponding time zones. It will be further complicated by the fact that cities with the same name exist, so you may have ambiguous input. For example, by Paris I suppose you intended the capital and largest city of France, Europe, but towns called Paris exist in other places too. I don’t know if a suitable database exists, you may search.

I can get you close, though, with what is built into Java. Time zones have IDs in the form region/city, for example Australia/Sydney and Asia/Dubai. The city used in naming the time zone is the largest populated area of the time zone, so even in the case where a country or state is only one time zone, the city needs not be the capital. But if the city coincides, we can find the zone.

    Set<String> zids = ZoneId.getAvailableZoneIds();

    String[] cityNames = { "Abu Dhabi", "Dubai", "Sydney", "Dhaka", "Paris", "Indianapolis", "São Tomé" };
    for (String cityName : cityNames) {
        String tzCityName = Normalizer.normalize(cityName, Normalizer.Form.NFKD)
                .replaceAll("[^\\p{ASCII}-_ ]", "")
                .replace(' ', '_');
        List<String> possibleTimeZones = zids.stream()
                .filter(zid -> zid.endsWith("/" + tzCityName))
                .collect(Collectors.toList());
        System.out.format("%-12s %s%n", cityName, possibleTimeZones);
    }

The output from this snippet is:

Abu Dhabi    []
Dubai        [Asia/Dubai]
Sydney       [Australia/Sydney]
Dhaka        [Asia/Dhaka]
Paris        [Europe/Paris]
Indianapolis [America/Indianapolis, America/Indiana/Indianapolis]
São Tomé     [Africa/Sao_Tome]

You will notice, though, that it didn’t find any time zone for Abu Dhabi because although the capital of the United Arab Emirates, it is not the largest city; Dubai is. You will notice too that two time zones were found for Indianapolis. The former is just an alias for the latter, though.

The city names used in the time zone database are the English names (when they exist) stripped of any accents. When a name is in two or three words, they are separated by underscores rather than spaces. So São Tomé becomes Sao_Tome. Therefore in the code I am performing this conversion. The way to strip off the accents was taken from another Stack Overflow answer, link below.

Links

  • List of tz database time zones on Wikipedia
  • Answer by Erick Robertson to Is there a way to get rid of accents and convert a whole string to regular letters?