Home >Java >javaTutorial >How Can I Accurately Convert Java Date/Time Objects Between Time Zones?
Problem:
Converting a date and time from one time zone to another can be challenging in Java. The code provided by the user for converting the current time from GMT to GMT 13 seems straightforward, but the same approach fails when setting a specific time. The user questions why the local machine's time zone is used in such cases.
Solution:
The confusion arises from the fact that when creating a new Date object without an explicit time zone, the time is assumed to be in UTC. However, when setting the time on a Calendar object using milliseconds (as in calendar.setTime(new Date(1317816735000L))), the assumption is that the time is in the time zone of the host machine.
To overcome this, you can explicitly set the time zone for the SimpleDateFormat object before formatting the time:
import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.TimeZone; Calendar calendar = Calendar.getInstance(); calendar.setTime(new Date(1317816735000L)); SimpleDateFormat sdf = new SimpleDateFormat("dd MMM yyyy HH:mm:ss z"); // Set the time zone for the formatter sdf.setTimeZone(TimeZone.getTimeZone("GMT+13")); // Format the time with the specified time zone String newZealandTime = sdf.format(calendar.getTime());
This code will return the date in the specified time zone (GMT 13) as a string.
Steps for Custom Date/Time Conversion:
The above is the detailed content of How Can I Accurately Convert Java Date/Time Objects Between Time Zones?. For more information, please follow other related articles on the PHP Chinese website!