I have a requirement where I have to convert timezone from UTC to a specific timezone and vice-versa taking into account day light saving. I am using java.util.TimeZone
class for it. Now, issue is that there are several hundred Ids for timezone which cannot be displayed to user.
As a work around now we have decided to have country list first and list time-zones for country selected. I am not able to get TimeZone
for an ISO country code.
Here is code which I am currently using to convert timezones,
Timestamp convertedTime = null;
try{
System.out.println("timezone: "+timeZone +", timestamp: "+timeStamp);
Locale locale = Locale.ENGLISH;
TimeZone destTimeZone = TimeZone.getTimeZone(timeZone);// TimeZone.getDefault();
System.out.println("Source timezone: "+destTimeZone);
DateFormat formatter = DateFormat.getDateTimeInstance(
DateFormat.DEFAULT,
DateFormat.DEFAULT,
locale);
formatter.setTimeZone(destTimeZone);
Date date = new Date(timeStamp.getTime());
System.out.println(formatter.format(date));
convertedTime = new Timestamp(date.getTime());
/*long sixMonths = 150L * 24 * 3600 * 1000;
Date inSixMonths = new Date(timeStamp.getTime() + sixMonths);
System.out.println("After 6 months: "+formatter.format(inSixMonths));
I need to find out timezone Id to be used in above code for given country ISO code.
Update: tried many things and below code gets me to list of timezones with 148 entries (which is still large). Can any one please help me to shorten it. Or, suggest some other way to either have a shorten list of timezones or get timezones for a country,
Code:
public class TimeZones {
private static final String TIMEZONE_ID_PREFIXES =
"^(Africa|America|Asia|Atlantic|Australia|Europe|Indian|Pacific)/.*";
private List<TimeZone> timeZones = null;
public List<TimeZone> getTimeZones() {
if (timeZones == null) {
initTimeZones();
}
return timeZones;
}
private void initTimeZones() {
timeZones = new ArrayList<TimeZone>();
final String[] timeZoneIds = TimeZone.getAvailableIDs();
for (final String id : timeZoneIds) {
if (id.matches(TIMEZONE_ID_PREFIXES)) {
timeZones.add(TimeZone.getTimeZone(id));
}
}
Collections.sort(timeZones, new Comparator<TimeZone>() {
public int compare(final TimeZone a, final TimeZone b) {
return a.getID().compareTo(b.getID());
}
});
}
I think ICU4J package will help you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With