Tuesday, April 26, 2011

Timezone Conversion with Daylight saving

Timezone conversion from one timezone to other timezone for the given time or hour string input.

While converting the timezone we have to consider DST standard also. in jdk 1.3. and 1.4 DST was not taken care internally by jdk, But from jdk 1.5 it is taken care.

What is daylight saving or DST?

Daylight Saving Time (or summertime as it is called in many countries) is a way of getting more light out of the day by advancing clocks by one hour during the summer. During Daylight Saving Time, the sun appears to rise one hour later in the morning, when people are usually asleep anyway, and sets one hour later in the evening, seeming to stretch the day longer.
About Daylight Saving Time.

for brief history on daylight visit the below link
http://en.wikipedia.org/wiki/Daylight_saving_time

In jDK we have a mehod inDaylightTime() in TimeZone class to check is given date is in DST for the timezone

ex : timeZone.inDaylightTime(new Date());

sample code :

public static boolean IsTimeZoneInDST(TimeZone timeZone) throws ParseException{
return timeZone.inDaylightTime(new Date());
}

now we have to convert the time from one timezone to another by using the timezone rawOffset.

sample :

public static Timestamp convert(Timestamp timeStamp, TimeZone fromTimeZone, TimeZone toTimeZone) {

// if null, convert from UTC
long offFrom = fromTimeZone == null ? 0 : fromTimeZone.getOffset(timeStamp.getTime());

// if null, convert to UTC
long offTo = toTimeZone == null ? 0 : toTimeZone.getOffset(timeStamp.getTime());

return new Timestamp(timeStamp.getTime()/1000*1000 + timeStamp.getNanos()/1000000 + offTo - offFrom);
}
now in above we have some thing fishy i.e

timeStamp.getTime()/1000*1000 + timeStamp.getNanos()/1000000

the above code was for the jdk 1.3 and 1.4, Because its was a bug in the jdk see the below link
http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4679060

sample TimeZoneConverter.java class download