Home > Java > javaTutorial > How to Convert Java Timestamps to Different Time Zones?

How to Convert Java Timestamps to Different Time Zones?

DDD
Release: 2024-11-19 10:52:02
Original
259 people have browsed it

How to Convert Java Timestamps to Different Time Zones?

Converting Java Timestamps to Different Time Zones

In Java, timestamps are initially in Greenwich Mean Time (GMT) by default. However, when dealing with user inputs from various time zones, converting timestamps to a user's specific time zone becomes necessary.

Consider this scenario: a user in Eastern Standard Time (EST) provides a timestamp of "5/1/2008 6:12 PM (EST)". The web service expects the timestamp in GMT, which is "5/1/2008 6:12 PM (GMT)".

To accurately convert timestamps across different time zones, a custom converter is needed. Here's the code for convertToGmt():

public static Calendar convertToGmt(Calendar cal) {

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

    // Milliseconds since epoch GMT
    long msFromEpochGmt = date.getTime();

    // Current offset from GMT at current date
    int offsetFromUTC = tz.getOffset(msFromEpochGmt);

    // Create a GMT calendar, set time, and add offset
    Calendar gmtCal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
    gmtCal.setTime(date);
    gmtCal.add(Calendar.MILLISECOND, offsetFromUTC);

    return gmtCal;
}
Copy after login

This method converts the input calendar to a GMT calendar, ensuring the timestamp is accurate in GMT for the web service. Note that this method does not currently handle daylight saving time changes.

The above is the detailed content of How to Convert Java Timestamps to Different Time Zones?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template