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 (DST) while converting date.
/**
* Convert Date from one timezone
to other timezone.
* This method also takes care of daylight saving time
* 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;
}
thanks it helped me :) to convert from UTC to CET
ReplyDeleteFOR utc
ReplyDeletepublic 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;
}
}
It helped. Thanks
ReplyDelete