I'm converting a UTC time to another timezone, using this method:
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date parsed = format.parse("2011-03-01 15:10:37");
TimeZone tz = TimeZone.getTimeZone("America/Chicago");
format.setTimeZone(tz);
String result = format.format(parsed);
So the input is 2011-03-01 15:10:37
but the output of this (value of result) is 2011-03-01 05:40:37
. While it seems off, and according to this link, it should be 2011-03-01 09:10:37
.
What am I doing wrong?
You need to take Daylight Savings into consideration. I do this by working out the offset (from UTC) in millieseconds. Something like this should work.
The
inDayLightTime(...)
method returns a boolean and must be passed a Date object in order for it to decide if that 'date' represents one during a DST period or not.Converting a date String of the format "2011-06-23T15:11:32" to out time zone.
It turns out the code was almost correct, what I didn't take into account was that when parsing the
String
to get aDate
object initially, it uses default systemTimeZone
, 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:You can Parse your date format and time zone according to your requirements. Try this snippet of code i hope it helpful for you.
Following code works fine for me to change a date from one tz to another. It considers the DayLightSaving also.