Java Convert Date to Another Time Zone
Tags: Java Date Java TimeZone SimpleDateFormat
In this Java tutorial, we learn the step by step how to convert a Date object to a date time String in another time zone in Java programming language.
How to convert Date to another time zone in Java
With a given Date object in Java, we can use the following steps to convert it to a date time String in another time zone.
- Step 1: create a new object of java.text.SimpleDateFormat with a specified date time format pattern.
- Step 2: create a new java.util.TimeZone in target time zone ID using the TimeZone.getTimeZone() static method.
- Step 3: assign the TimeZone object to SimpleDateFormat objec using the SimpleDateFormat.setTimeZone() method.
- Step 4: Use the SimpleDateFormat.format() method to format the Date value into date time String in target time zone.
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-M-yyyy HH:mm:ss");
TimeZone timeZone = TimeZone.getTimeZone("Europe/Paris");
simpleDateFormat.setTimeZone(timeZone);
String result = simpleDateFormat.format(date);
In the following example Java program, we show how to convert a Date value from system default time zone to a date time String in Europe/Paris time zone.
DateTimeZoneExample1.java
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
public class DateTimeZoneExample1 {
public static void main(String... args) {
Date date = new Date();
// Convert Date object to another time zone
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-M-yyyy HH:mm:ss");
TimeZone timeZone = TimeZone.getTimeZone("Europe/Paris");
simpleDateFormat.setTimeZone(timeZone);
String result = simpleDateFormat.format(date);
System.out.println("Current time zone: " + TimeZone.getDefault().getID());
System.out.println("Date time in current time zone: " + date);
System.out.println("Date time in Europe/Paris time zone: " + result);
}
}
Current time zone: Asia/Bangkok
Date time in current time zone: Tue Oct 18 22:54:47 ICT 2022
Date time in Europe/Paris time zone: 18-10-2022 17:54:47
Happy Coding 😊