Saturday, September 21, 2013

Get current time in different TimeZone

This example call setTimeZone() method of GregorianCalendar object to switch to different TimeZone, and get the current time in the target timezone.

Get current time in different TimeZone


package java_timezone;

import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Locale;
import java.util.TimeZone;

/**
 *
 * @web http://java-buddy.blogspot.com/
 */
public class Java_TimeZone {

    public static void main(String[] args) {
        System.out.println("Default TimeZone: " + 
                TimeZone.getDefault().getDisplayName());
        
        GregorianCalendar now = new GregorianCalendar();
        
        String AMPM;
        if(now.get(Calendar.AM_PM) == Calendar.AM){
            AMPM = "AM";
        }else{
            AMPM = "PM";
        }
        
        System.out.println(
                now.get(Calendar.YEAR) + "-" +
                now.get(Calendar.MONTH) + "-" +
                now.get(Calendar.DAY_OF_MONTH) + " " +
                AMPM + ":" +
                now.get(Calendar.HOUR) + ":" +
                now.get(Calendar.HOUR_OF_DAY) + ":" +
                now.get(Calendar.MINUTE));
        
        String[] availableIDs = TimeZone.getAvailableIDs();
        System.out.println("number of available TimeZone IDs: " + 
                availableIDs.length);
        
        for (String id : availableIDs){
            System.out.print(
                    "ID: " + id + 
                    " | " + TimeZone.getTimeZone(id).getDisplayName());
            
            System.out.print("@");
            
            now.setTimeZone(TimeZone.getTimeZone(id));
            String idAMPM;
            if(now.get(Calendar.AM_PM) == Calendar.AM){
                idAMPM = "AM";
            }else{
                idAMPM = "PM";
            }
            System.out.println(
                now.get(Calendar.YEAR) + "-" +
                now.get(Calendar.MONTH) + "-" +
                now.get(Calendar.DAY_OF_MONTH) + " " +
                idAMPM + ":" +
                now.get(Calendar.HOUR) + ":" +
                now.get(Calendar.HOUR_OF_DAY) + ":" +
                now.get(Calendar.MINUTE));
        }
    }
}

No comments:

Post a Comment