Home  >  Article  >  Java  >  How to Convert EST Timestamps to GMT in Java?

How to Convert EST Timestamps to GMT in Java?

Barbara Streisand
Barbara StreisandOriginal
2024-11-12 16:36:02778browse

How to Convert EST Timestamps to GMT in Java?

How to Convert Time Zones Using Java Timestamps

In this scenario, you have a timestamp in the EST time zone and need to convert it to GMT for a web service call. Here's a detailed explanation:

Converting from EST to GMT

The problem arises because the timestamp value is initially assumed to be in GMT, but it may actually be in a different local time zone (EST in this case). To convert the user's parameter from EST to GMT, you need to account for the time difference between the two time zones.

Using the Calendar Class

You're using the Calendar class to manipulate the timestamp. However, you should be aware that the Calendar class always works in milliseconds since the epoch, regardless of the time zone you specify. This means that when you create a Calendar from a Timestamp using Calendar.getInstance(GMT_TIMEZONE), the underlying date is not adjusted to match the GMT time zone.

Solution: Adjusting for Time Zone Offset

To accurately convert the timestamp to GMT, you need to account for the time zone offset. The following code snippet provides a solution:

public static Calendar convertToGmt(Calendar cal) {

    Date date = cal.getTime();
    TimeZone tz = cal.getTimeZone();

    // Compute milliseconds since epoch in GMT
    long msFromEpochGmt = date.getTime();

    // Get offset from UTC in milliseconds at the given time
    int offsetFromUTC = tz.getOffset(msFromEpochGmt);

    // Create a new Calendar in GMT and adjust the date with the offset
    Calendar gmtCal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
    gmtCal.setTime(date);
    gmtCal.add(Calendar.MILLISECOND, offsetFromUTC);

    return gmtCal;
}

Example Output

If you pass the current time (in EDT) into the convertToGmt method, you will get the following output:

DEBUG - input calendar has date [Thu Oct 23 12:09:05 EDT 2008]
DEBUG - offset is -14400000
DEBUG - Created GMT cal with date [Thu Oct 23 08:09:05 EDT 2008]

This shows that 12:09:05 EDT has been successfully converted to 08:09:05 GMT.

The above is the detailed content of How to Convert EST Timestamps to GMT in Java?. 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