To convert a Date object to a Date object in a specific time zone, you can use the following steps:
SimpleDateFormat
class and set the time zone using the setTimeZone()
method.parse()
method of the SimpleDateFormat
class to convert the Date object to a string in the desired time zone.SimpleDateFormat
class and set the time zone using the setTimeZone()
method.parse()
method of the SimpleDateFormat
class again to convert the string back to a Date object in the desired time zone.Here is an example code in Java:
import java.util.Date;
import java.text.SimpleDateFormat;
import java.util.TimeZone;
public class DateConverter {
public static void main(String[] args) throws Exception {
Date date = new Date();
SimpleDateFormat formatter1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
formatter1.setTimeZone(TimeZone.getTimeZone("UTC"));
String dateString = formatter1.format(date);
SimpleDateFormat formatter2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
formatter2.setTimeZone(TimeZone.getTimeZone("America/New_York"));
Date newDate = formatter2.parse(dateString);
System.out.println("Original Date: " + date);
System.out.println("Converted Date: " + newDate);
}
}
In this example, the Date
object date
is converted to a string in the UTC time zone, and then converted back to a Date
object in the "America/New_York" time zone. The output would be something like:
Original Date: Thu Apr 15 22:58:07 UTC 2021
Converted Date: Thu Apr 15 18:58:07 EDT 2021
Asked: 2021-07-11 11:00:00 +0000
Seen: 7 times
Last updated: Jul 31 '22