Monday, 23 July 2012

Display Current Time in Different Time Zones in Java

To display time in a specific time zone we can use the Calendar class. After it has been created we set the time zone on the instance using the method setTimeZone.After that we can just query the instance for retrieving the required fields.


The complete source code is given below:



import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.TimeZone;

public class DisplayTimeInDiffTimeZones {

 public static void main(String[] args) {

  Calendar cal = Calendar.getInstance();

  SimpleDateFormat fmt = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss z");

  System.out.println("Time in default Timezone: "
    + fmt.format(cal.getTime()));

  cal.setTimeZone(TimeZone.getTimeZone("GMT"));

  System.out
    .println("Time in GMT Timezone: " + fmt.format(cal.getTime()));

 }

}

The output is:



Time in default Timezone: 23/07/2012 04:29:41 IST
Time in GMT Timezone: 23/07/2012 04:29:41 IST


You can't convert a Date into a different time zone, but you can use Java's SimpleDateFormat class to format a Date into the time zone of your choice.

The complete source code is given below:


import java.text.SimpleDateFormat;

import java.util.Date;

import java.util.TimeZone;

public class DisplayTimeInDiffTimeZones {

 public static void main(String[] args) {

  Date current = new Date();

  SimpleDateFormat fmt = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss z");

  System.out.println("Time in default Timezone: " + fmt.format(current));

  fmt.setTimeZone(TimeZone.getTimeZone("GMT"));

  System.out.println("Time in GMT Timezone: " + fmt.format(current));

 }

}

The output is


Time in default Timezone: 23/07/2012 03:59:54 IST

Time in GMT Timezone: 23/07/2012 10:29:54 GMT




The links that may help you:



No comments:

Post a Comment