Java: Timezone Correction/Conversion with Daylight Savings Time settings


Have tried out a couple of code snippets to handle timezone corrections in Java code that’ll take into account Daylight Savings Time (DST) settings. None of them really suited our need; so I had to modify a particular code snippet which I found to be closer to what I was expecting.

Here’s the modified code:.

private static Date offsetTimeZone(Date date, String fromTZ, String toTZ){

// Construct FROM and TO TimeZone instances
TimeZone fromTimeZone = TimeZone.getTimeZone(fromTZ);
TimeZone toTimeZone = TimeZone.getTimeZone(toTZ);

// Get a Calendar instance using the default time zone and locale.
Calendar calendar = Calendar.getInstance();

// Set the calendar's time with the given date
calendar.setTimeZone(fromTimeZone);
calendar.setTime(date);

System.out.println("Input: " + calendar.getTime() + " in " + fromTimeZone.getDisplayName());

// FROM TimeZone to UTC
calendar.add(Calendar.MILLISECOND, fromTimeZone.getRawOffset() * -1);

if (fromTimeZone.inDaylightTime(calendar.getTime())) {
calendar.add(Calendar.MILLISECOND, calendar.getTimeZone().getDSTSavings() * -1);
}

// UTC to TO TimeZone
calendar.add(Calendar.MILLISECOND, toTimeZone.getRawOffset());

if (toTimeZone.inDaylightTime(calendar.getTime())) {
calendar.add(Calendar.MILLISECOND, toTimeZone.getDSTSavings());
}

return calendar.getTime();

}

Sample Method Invocation: offsetTimeZone(new Date(), “Asia/Kolkata”, “US/Central”)

One good thing about this solution is that it’ll take care of DST settings in both the timezones (FROM and TO).

About these ads

About this entry