Home Java Javadate Java Time Zone Example
Questions:Ask|Latest



Java Time Zone Example
Posted on: October 14, 2008 By Deepak Kumar
In this section we have written a java program which will take two Time Zone IDs as its argument and then convert the time between provided time zone IDs.

Java Time Zone Example

     

Converting time between time zones

In this section we have written a java program which will take two Time Zone IDs as its argument and then convert the time between provided time zone IDs.

In our program we have firstly created a new date object and then after we have created two time zone class's objects with according to the provided time zone IDs.

TimeZone firstTime = TimeZone.getTimeZone(args[0]);   
TimeZone secondTime = TimeZone.getTimeZone(args[1]);

Above lines of code creates two objects of TimeZone as firstTime and secondTime. We have called getTimeZone() method to create these objects.

Here is the full example code of ConvertTimeZone.java as follows:

ConvertTimeZone.java

  ///////////////////////////////////
 // Convert time between time zone //
///////////////////////////////////

import java.util.Date;
import java.text.SimpleDateFormat;
import java.text.DateFormat;
import java.util.TimeZone;
 
public class ConvertTimeZone {
  public static void main(String[] args) {
  Date date = new Date();
  DateFormat firstFormat = new SimpleDateFormat();
  DateFormat secondFormat = new SimpleDateFormat();
  TimeZone firstTime = TimeZone.getTimeZone(args[0]);
  TimeZone secondTime = TimeZone.getTimeZone(args[1]);
  firstFormat.setTimeZone(firstTime);
  secondFormat.setTimeZone(secondTime);
  System.out.println("-->"+args[0]+": " + firstFormat.format(date));
  System.out.println("-->"+args[1]+": " + secondFormat.format(date));
  }
}

Output:

Compile the ConvertTimeZone.java file and when executing them provide the two Time zone Ids from which to which time is to be converted. Here in above program we have provided two command line arguments as IST and GMT.

C:\DateExample>javac ConvertTimeZone.java

C:\DateExample>java ConvertTimeZone IST GMT
-->IST: 10/11/08 4:16 PM
-->GMT: 10/11/08 10:46 AM

C:\DateExample>

Download Source Code


Recommend the tutorial

Ask Questions?    Discuss: Java Time Zone Example  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments
chandra sekhar
August 16, 2011
time Zone conversion

good and simple