Thursday, October 11, 2012

How to get Current Time based on Time Zone using java

 import java.util.*;
 import java.text.*;
 public class time_Zone {
     public static void main(String[] args) {
         TimeZone tz = Calendar.getInstance().getTimeZone();
         System.out.println("TimeZone: "+tz.getDisplayName());
         System.out.println("ID: "+tz.getID());

        final Date currentTime = new Date();

        final SimpleDateFormat sdf = new SimpleDateFormat("EEE, MMM d, yyyy hh:mm:ss a z");

        // Give it to me in US-Pacific time.
        sdf.setTimeZone(TimeZone.getTimeZone("America/Los_Angeles"));
        System.out.println("LA time: " + sdf.format(currentTime));

        // Give it to me in GMT-0 time.
        sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
        System.out.println("GMT time: " + sdf.format(currentTime));

        // Or maybe Zagreb local time.
        sdf.setTimeZone(TimeZone.getTimeZone("Europe/Zagreb"));
        System.out.println("Zagreb time: " + sdf.format(currentTime));

        // Even 10 hours and 10 minutes ahead of GMT
        sdf.setTimeZone(TimeZone.getTimeZone("GMT+0010"));
        System.out.println("10/10 ahead time: " + sdf.format(currentTime));

        System.out.println("INDIA ");

        sdf.setTimeZone(TimeZone.getTimeZone(tz.getID()));
        System.out.println("10/10 ahead time: " + sdf.format(currentTime));

        /*Date date = new Date();
          String TimeZoneIds[] = TimeZone.getAvailableIDs();
          for(int i = 0; i < TimeZoneIds.length; i++){
              TimeZone tz = TimeZone.getTimeZone(TimeZoneIds[i]);
              String tzName = tz.getDisplayName(tz.inDaylightTime(date), TimeZone.LONG);
              System.out.print(TimeZoneIds[i] + ": ");
              // Get the number of hours from GMT
              int rawOffset = tz.getRawOffset();
              int hour = rawOffset / (60*60*1000);
              int minute = Math.abs(rawOffset / (60*1000)) % 60;
              System.out.println(tzName + " " + hour + ":" + minute);
          }*/
       
      }
}

0 comments:

Post a Comment