Home >Java >javaTutorial >How Can I Accurately Convert Java Date/Time Objects Between Time Zones?

How Can I Accurately Convert Java Date/Time Objects Between Time Zones?

DDD
DDDOriginal
2024-11-28 11:14:15666browse

How Can I Accurately Convert Java Date/Time Objects Between Time Zones?

Conversion of Date/Time to a Specific Time Zone in Java

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:

  1. Create a Calendar object and set the time and date.
  2. Specify the initial time zone using sdf.setTimeZone(TimeZone.getTimeZone("GMT")).
  3. Format the time using sdf.format(calendar.getTime()).
  4. Set the desired time zone to the SimpleDateFormat object using sdf.setTimeZone(TimeZone.getTimeZone("GMT 13")).
  5. Reformat the time using the new time zone to get the converted value.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn