Converting TimeZones

Converting timezones can be a bit complicated if you are attempting to do it for the first time. There are problems using the java.util classes that can introduce bugs in your application.


Let's say you have a java.util.date field that you retrieved from the database and you want to display this value in the user's local timezone.

java.util.Date always reflects UTC since they do not have timezones. So you cannot convert a Date from one timezone to another. Only a Calendar or a textual representation of a date can be converted into a different time zone.

So the first step to do this would be convert the Date to a Calendar.

The normal way of doing it would be


You would then use a DateFormat to display this time in whatever format and timezone is desired.

Example:


But Calendar.getTime() is not recommended and there is a bug explaining the workaround.
Bug: http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4031021

So we would use a method like the one below to get the time value out of the Calendar object.



So the date display would now be:


But using Calendar.setTime() might not convert the UTC date into a local timezone correctly. The problem I noticed was a one hour difference when the UTC date ends up in the next day corresponding to the user's local time. Also, this only occurs if you are dealing with a day later than the current day.

Example: Lets say the UTC date value is Dec 21st 2010 2:45 AM
We need this value to be converted to a user's local timezone, let's say EST time.

So the correct converted date would be
Dec 20th 2010 9:45 PM (after DST change)

There is an alternative way of converting timezones to fix the above problem.

Step 1:
Convert the Date field to a Calendar object. All timezone conversions should be done in a java.util.Calendar.

Note that only the "time" field is stored in the resulting Calendar object. The date will be set in Step 4. This workaround is required for the problem described above to be resolved.




Step 2:

Convert the timezone on the Time field:



The resulting Calendar object will have the correct time set, but will still have today's(current day's) date.

Step 3:

Calculate the difference between the current day and the original date that had to be converted:



Step 4:
Add the difference to the converted Calendar object. The final code combining all the above steps is as follows:






Reference:
Date and time in Java

0 comments: