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 this entry
You’re currently reading “Java: Timezone Correction/Conversion with Daylight Savings Time settings,” an entry on Singaram's Tech Musings
- Published:
- June 23, 2011 / 7:44 PM
- Category:
- Coding tips, Java

4 Comments
Jump to comment form | comment rss [?] | trackback uri [?]