Pages

Monday, 24 September 2012

Convert java util Date From one Timezone To another Timezone In Java

How to convert java.util date from one Timezone To another Timezone?



      Here is the simple method which converts one Timezone To another and returns util date. Also most important thing is that it handles daylight saving time (DSTwhile converting date.



/**
* Convert Date from one timezone to other timezone.
* This method also takes care of daylight saving time
* @param dt
* @param from
* @param to
* @return
*/
public static Date convertFromOneTimeZoneToOhter(Date dt,String from,String to ) {

      TimeZone fromTimezone =TimeZone.getTimeZone(from);//get Timezone object
      TimeZone toTimezone=TimeZone.getTimeZone(to);
             
      long fromOffset = fromTimezone.getOffset(dt.getTime());//get offset
      long toOffset = toTimezone.getOffset(dt.getTime());
     
      //calculate offset difference and calculate the actual time
      long convertedTime = dt.getTime() - (fromOffset - toOffset);
      Date d2 = new Date(convertedTime);
     
      return d2;
}