Thursday, February 13, 2014

timezone get list, time zone id, time zone name, time offset using java


/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package time.zone;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Locale;
import java.util.TimeZone;

/**
 *
 * @author Pritom Kumar Mondal
 */
public class TimeZoneList {
    public static void main(String[] args) {
        String supportedPattern = "^(Africa|America|Asia|Atlantic|Australia|"
                + "Europe|Indian|Pacific)/.*";
        String[] timeZoneIdList = TimeZone.getAvailableIDs();
        List<TimeZone> timeZoneList = new ArrayList<TimeZone>();
        for(String id : timeZoneIdList) {
            if(id.matches(supportedPattern)) {
                timeZoneList.add(TimeZone.getTimeZone(id));
            }
        }
        Collections.sort(timeZoneList, new Comparator<TimeZone>() {
            public int compare(final TimeZone a, final TimeZone b) {
                return a.getID().compareTo(b.getID());
            }
        });
        for(TimeZone timeZone : timeZoneList) {
            String zoneId = timeZone.getID();
            String displayName = timeZone.getDisplayName();
            double offset = (double) timeZone.getRawOffset() / 1000 / 60 / 60;
            String minute = ((offset - (int) offset) * 60) > 0 ? (" & " + (int) 
                    ((offset - (int) offset) * 60) + " minute") : "";
            System.out.println("Zone id: " + zoneId + ", name: " + displayName + ""
                    + ", offset: " + (int) offset + " hour" + minute);
        }
    }
}

And output would something like this...

.
.
.
Zone id: Asia/Bangkok, name: Indochina Time, offset: 7 hour
Zone id: Asia/Beirut, name: Eastern European Time, offset: 2 hour
Zone id: Asia/Bishkek, name: Kirgizstan Time, offset: 6 hour
Zone id: Asia/Brunei, name: Brunei Time, offset: 8 hour
Zone id: Asia/Calcutta, name: India Standard Time, offset: 5 hour & 30 minute
Zone id: Asia/Choibalsan, name: Choibalsan Time, offset: 8 hour
Zone id: Asia/Chongqing, name: China Standard Time, offset: 8 hour
Zone id: Asia/Chungking, name: China Standard Time, offset: 8 hour
Zone id: Asia/Colombo, name: India Standard Time, offset: 5 hour & 30 minute
Zone id: Asia/Dacca, name: Bangladesh Time, offset: 6 hour
Zone id: Asia/Damascus, name: Eastern European Time, offset: 2 hour
Zone id: Asia/Dhaka, name: Bangladesh Time, offset: 6 hour
.
.
.

No comments:

Post a Comment