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; }
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!