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;
}

3 comments:

  1. thanks it helped me :) to convert from UTC to CET

    ReplyDelete
  2. FOR utc

    public static Date getClientTimeFromUTC(Date utcDate, String clientTimezone)
    {
    if (utcDate == null)
    return null;
    else
    {
    long utcTimeinMilliSeconds = utcDate.getTime();
    TimeZone timezone = TimeZone.getTimeZone(clientTimezone); // timezone set in client's profile
    long timezoneOffset = timezone.getOffset(utcTimeinMilliSeconds); // timezone.getRawOffset()+timezone.getDSTSavings();
    Date tmpDate = new Date(utcTimeinMilliSeconds + timezoneOffset);
    //System.out.println("tmpDate:=----------"+tmpDate);
    return tmpDate;// calendar;
    }
    }

    ReplyDelete