How to Handle Calendar TimeZones Using Java
Question:
You have a Timestamp from your application that may originate from any TimeZone. However, the data must be sent to a WebService that assumes it's always in GMT. You need to convert the user's input time from their local TimeZone to GMT without their knowledge.
Answer:
Java's TimeZone handling can be confusing. While Timestamps are typically stored in GMT, the Calendar class uses the system's current TimeZone by default. To address this challenge, consider the following:
import java.util.Calendar; import java.util.TimeZone; public class ConvertTimeZone { public static void main(String[] args) { // Example input time (EST) Calendar input = Calendar.getInstance(TimeZone.getTimeZone("EST")); input.set(2008, Calendar.MAY, 1, 18, 12, 0); // Create a Calendar in GMT Calendar gmt = convertToGmt(input); // Output the converted time (GMT) System.out.println(gmt.getTime()); // 2008-05-01 11:12:00 GMT } public static Calendar convertToGmt(Calendar cal) { Date date = cal.getTime(); TimeZone tz = cal.getTimeZone(); long msFromEpochGmt = date.getTime(); // Convert to milliseconds since epoch in GMT int offsetFromUTC = tz.getOffset(msFromEpochGmt); // Create a new Calendar in GMT and adjust for the offset Calendar gmtCal = Calendar.getInstance(TimeZone.getTimeZone("GMT")); gmtCal.setTime(date); gmtCal.add(Calendar.MILLISECOND, offsetFromUTC); return gmtCal; } }
This code takes the following steps:
By utilizing this approach, you can accurately convert the user's input time from any TimeZone to GMT, ensuring data compatibility with the WebService.
The above is the detailed content of How to Convert a Timestamp From Any TimeZone to GMT in Java?. For more information, please follow other related articles on the PHP Chinese website!