Convert dateTime from one Time-zone to another

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

public class ConvertTimeZone {
public static void main(String args[]) {
// here we are assuming that we have
// date/Time in Africa/Harare(UTC+02)
// Time zone
// Africa/Harare -> 02/29/2012 23:59:36
String fromTimeZone = "Africa/Harare";
// we want to convert it into
// Asia/Riyadh(UTC+03) Time Zone
// Asia/Riyadh -> 03/01/2012 00:59:36
String toTimeZone = "Asia/Riyadh";
String format = "MM/dd/yyyy kk:mm:ss";
int dd = 29;// day of the month
int MM = 02;// month
int yyyy = 2012;// year
int kk = 23;// hours in 24 hrs format
int mm = 59;// minutes
int ss = 36;// seconds
ConvertTimeZone ctz = new ConvertTimeZone();
ctz.convertTimeZoneFormat(dd, MM, yyyy,
kk, mm, ss, fromTimeZone, toTimeZone, format);

}

public void convertTimeZoneFormat(int dd, int MM, int yyyy,
int kk, int mm, int ss, String fromTimeZone,
String toTimeZone, String format) {
String convertedDateTime = "";
Calendar calendar = Calendar.getInstance(TimeZone
.getTimeZone(fromTimeZone));
calendar.set(yyyy, MM, dd, kk, mm, ss);

SimpleDateFormat sdfSrc = new SimpleDateFormat(format);
sdfSrc.setTimeZone(TimeZone.getTimeZone(fromTimeZone));
System.out.println(fromTimeZone + " : "
+ sdfSrc.format(calendar.getTime()));

SimpleDateFormat sdfDest = new SimpleDateFormat(format);
sdfDest.setTimeZone(TimeZone.getTimeZone(toTimeZone));
convertedDateTime = sdfDest.format(calendar.getTime());
System.out.println(toTimeZone + " : " + convertedDateTime);
}
}

 

Rate this post

Leave a Reply