I would like to construct a timezone list to show it to users to select. The display name has to be like:
( GMT 5:30 ) India Standard Time(Asia/Calcutta)
I am taking all timezones with TimeZone.getAvailableIDs()
and constructing the list. The code I wrote is:
String[] timeZones = TimeZone.getAvailableIDs();
List<String> tzList = new ArrayList<String>();
for (String timeZone : timeZones)
{
TimeZone tz = TimeZone.getTimeZone(timeZone);
StringBuilder timeZoneStr = new StringBuilder();
timeZoneStr.append("( GMT ").append(tz.getRawOffset() / (60 * 60 * 1000)).append(" ) ").append(tz.getDisplayName()).append("(").append(timeZone).append(")");
tzList.add(timeZoneStr.toString());
System.out.println(timeZoneStr.toString());
}
A snippet of the output would be like:
( GMT 5 ) Maldives Time(Indian/Maldives)
( GMT 5 ) Pakistan Time(PLT)
( GMT 5 ) India Standard Time(Asia/Calcutta)
( GMT 5 ) India Standard Time(Asia/Kolkata)
( GMT 5 ) India Standard Time(IST)
But the output I need to get is:
( GMT 5:0 ) Maldives Time(Indian/Maldives)
( GMT 5:0 ) Pakistan Time(PLT)
( GMT 5:30 ) India Standard Time(Asia/Calcutta)
( GMT 5:30 ) India Standard Time(Asia/Kolkata)
( GMT 5:30 ) India Standard Time(IST)
What should I do to get 5:30?
Another solution with the proper formatting :
Just use a
SimpleDateFormat
with theXXX
timezone pattern (produces an ISO 8601 timezone)Source: http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html#iso8601timezone
You should switch the timezone forming line to:
I think this is the answer you're looking for. However, you may still format the minutes, as they only show one digit when the time offset is, for example 12 hours. It's shown as 12:0.
A more readable answer is the following:
This also correctly displays e.g.
5:00
and5:30
. The use ofString.format()
makes the final string easier to determine when reading the code. The use of theTimeUnit
class simplifies the maths.Offset timezone using below method :