» Time Zone Conversion with java.util.Date
Posted by Anders Østergaard Jensen on 3/9 2010 at 3:54 AMWhen building global web sites it is often necessary to display timestamps within the user’s own time zone. Ruby on Rails contains built-in functionality for this, whereas Java requires a more manual approach. In the following I will describe how such time zone conversion (and mapping) is easily implemented in Java.
The following method creates a time zone conversion from a standard java.util.Date (which defaults to the machine’s local time zone) to a specific time zone:
public static String formatUSDate(Date d, String tz) {
DateFormat fmt = new SimpleDateFormat("EEE, d/MM/yyyy 'at' KK:mm a Z");
TimeZone zone = getTimeZone(tz);
fmt.setTimeZone(zone);
return fmt.format(d);
}
The above method depends on the following support function that searches through the Java library of supported time zones (with lower case matching). If no match is found, getDefault() is returned. According to the SDK Javadoc, the default time zone depends on your system locale (if you are in Copenhagen, the standard time zone will be Europe/Copenhagen).
public static TimeZone getTimeZone(String tz) {
TimeZone retVal;
for (String id: TimeZone.getAvailableIDs()) {
if (id.toLowerCase().contains(tz.toLowerCase())) {
retVal = TimeZone.getTimeZone(id);
return retVal;
}
}
return TimeZone.getDefault();
}
Using the lowercase match search is especially useful if you are using time zones across different applications or frameworks with the same database. Fx. Ruby on Rails only stores the selected session time zone with the last identifier (e.g. ‘Copenhagen’ rather than ‘Europe/Copenhagen’), which makes it impossible to implement a one-to-one mapping between the two environments. Using getTimeZone(”Sydney”) or getTimeZone(”Copenhagen”) will thus return the Java time zone “Australia/Sydney” and ”Europe/Copenhagen” respectively.
Finally, the SimpleDateFormat lets you format the now converted Date representation to a localized format. Thus, the user can now also choose from different date formats in your application. This Javadoc link clarifies the different formatting options. For instance, a proper date representation for the Danish calendar would be:
DateFormat fmt = new SimpleDateFormat("d/MM/yyyy 'kl.' HH:mm Z");
Please let us know if you have further efficient methods for time zone conversion in Java and across different platforms.



