Converting UTC dates to other timezones
It turns out the code was almost correct, what I didn't take into account was that when parsing the String
to get a Date
object initially, it uses default system TimeZone
, so the source date was not in UTC as I expected.
The trick was to set the timezone when parsing the date to UTC and then set it to destination TimeZone
. Something like this:
SimpleDateFormat sourceFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
sourceFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
Date parsed = sourceFormat.parse("2011-03-01 15:10:37"); // => Date is in UTC now
TimeZone tz = TimeZone.getTimeZone("America/Chicago");
SimpleDateFormat destFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
destFormat.setTimeZone(tz);
String result = destFormat.format(parsed);
Converting a date String of the format "2011-06-23T15:11:32" to out time zone.
private String getDate(String dateString) {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
Date value = null;
try {
value = formatter.parse(dateString);
} catch (ParseException e) {
e.printStackTrace();
}
SimpleDateFormat dateFormatter = new SimpleDateFormat("dd/MM/yyyy hh:mmaa");
dateFormatter.setTimeZone(TimeZone.getDefault());
String dt = dateFormatter.format(value);
return dt;
}
Following code works fine for me to change a date from one tz to another. It considers the DayLightSaving also.
public static Calendar changeTimezoneOfDate(Date date, TimeZone fromTZ, TimeZone toTZ) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
long millis = calendar.getTimeInMillis();
long fromOffset = fromTZ.getOffset(millis);
long toOffset = toTZ.getOffset(millis);
long convertedTime = millis - (fromOffset - toOffset);
Calendar c = Calendar.getInstance();
c.setTimeInMillis(convertedTime);
return c;
}