How to set time zone of a java.util.Date?
To set the time zone of a java.util.Date
object in Java, you can use the Calendar
class.
Here is an example of how to set the time zone of a Date
object to the Pacific Time zone:
Date date = new Date();
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.setTimeZone(TimeZone.getTimeZone("America/Los_Angeles"));
date = calendar.getTime();
This will create a new Calendar
object with the default time zone and set its time to the specified Date
object. It will then set the time zone of the Calendar
object to the Pacific Time zone and retrieve the adjusted Date
object.
You can use the TimeZone.getTimeZone
method to get a TimeZone
object for a given time zone ID. A list of time zone IDs can be found in the TimeZone
class documentation or by calling the getAvailableIDs
method.
Keep in mind that the Date
class does not store the time zone information, and the time zone is only used to adjust the date and time values when the Date
object is converted to or from a Calendar
object.
If you want to store the time zone information in the Date
object, you can use the java.time.ZonedDateTime
class from the Java 8 Date and Time API, which represents a date-time with a time zone.
For example:
ZonedDateTime zdt = ZonedDateTime.of(LocalDateTime.now(), ZoneId.of("America/Los_Angeles"));
Date date = Date.from(zdt.toInstant());
This will create a new ZonedDateTime
object with the current date and time and the Pacific Time zone, and convert it to a Date
object using the toInstant
method and the Date.from
method. The time zone information will be preserved in the Date
object.