Ask Your Question
0

How can a Date object be converted to a Date object in a specific time zone?

asked 2021-07-11 11:00:00 +0000

huitzilopochtli gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2022-07-31 06:00:00 +0000

ladyg gravatar image

To convert a Date object to a Date object in a specific time zone, you can use the following steps:

  1. Create a new instance of the SimpleDateFormat class and set the time zone using the setTimeZone() method.
  2. Use the parse() method of the SimpleDateFormat class to convert the Date object to a string in the desired time zone.
  3. Create a new instance of the SimpleDateFormat class and set the time zone using the setTimeZone() method.
  4. Use the 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
edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2021-07-11 11:00:00 +0000

Seen: 7 times

Last updated: Jul 31 '22