Java Convert Calendar to Another Time Zone
Tags: Java Calendar Java TimeZone SimpleDateFormat
In this Java tutorial, we learn step by step how to convert a Calendar object to a date time String in another time zone in Java program.
How to convert Calendar to another time zone in Java
With a given Calendar object in Java, we can convert it to a date time String in another time zone with the following steps.
- Step 1: initialize java.text.SimpleDateFormat object with specified date time format.
- Step 2: create new instance of java.util.TimeZone with the target time zone ID using the TimeZone.getTimeZone() method
- Step 3: assign the TimeZone value to SimpleDateFormat object using the SimpleDateFormat.setTimeZone() method.
- Step 4: use the SimpleDateFormat.format() method to format the Calendar’s date time to target time zone.
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-M-yyyy HH:mm:ss");
TimeZone timeZone = TimeZone.getTimeZone("Australia/Sydney");
simpleDateFormat.setTimeZone(timeZone);
String result = simpleDateFormat.format(calendar.getTime())
In the following example Java program, we learn how to convert a Calendar value from default system time zone to date time in Australia/Sydney time zone.
CalendarTimeZoneExample1.java
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.TimeZone;
public class CalendarTimeZoneExample1 {
public static void main(String... args) {
Calendar calendar = Calendar.getInstance();
// Convert Calendar object to another time zone
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-M-yyyy HH:mm:ss");
TimeZone timeZone = TimeZone.getTimeZone("Australia/Sydney");
simpleDateFormat.setTimeZone(timeZone);
String result = simpleDateFormat.format(calendar.getTime());
System.out.println("Current time zone: " + calendar.getTimeZone().getID());
System.out.println("Date time in current time zone: " + calendar.getTime());
System.out.println("Date time in Australia/Sydney time zone: " + result);
}
}
Current time zone: Asia/Bangkok
Date time in current time zone: Tue Oct 18 22:31:50 ICT 2022
Date time in Australia/Sydney time zone: 19-10-2022 02:31:50
Happy Coding 😊