W3docs

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.

To interpret a java.util.Date object in a specific time zone, you can use the Calendar class. However, keep in mind that the Date class does not store time zone information; it only holds the number of milliseconds since the Unix epoch. Therefore, you cannot actually "set" a time zone on a Date object.

Here is an example of how to interpret a Date object in the Pacific Time zone:


Date date = new Date();
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.setTimeZone(TimeZone.getTimeZone("America/Los_Angeles"));

This code sets the time zone of the Calendar object to Pacific Time. Note that calendar.getTime() returns a Date representing the exact same instant (same epoch milliseconds). Changing the Calendar's time zone only affects how the Calendar calculates fields (like hour or day of month) or formats the date. The Date object itself remains unchanged.

If your goal is to display the date in a specific time zone, you should use a formatter rather than modifying the Date itself. For legacy code, SimpleDateFormat applies the time zone during output:

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z");
sdf.setTimeZone(TimeZone.getTimeZone("America/Los_Angeles"));
String formatted = sdf.format(date);

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.

If you need to work with time zone-aware values, you can use the java.time.ZonedDateTime class from the Java 8 Date and Time API instead of java.util.Date. Note that java.util.Date is deprecated for date-time manipulation and does not store time zone information.

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. For modern applications, you should use ZonedDateTime directly instead of converting to Date. If you must convert it to a legacy Date object, you can use Date.from(zdt.toInstant()), but note that the Date class remains timezone-agnostic and will not preserve the time zone information.