Possible Duplicate:
Timezone conversion
I have a date in UTC, how to convert it to other timezone?
Despite what the output of Date.toString()
suggests, Date
instances are not timezone aware. They simply represent a point in time, irrespective to the timezone. So if you have a Date
instance, there is nothing more you need to do. And what if you have time in one time zone and you want to know what is the time in other time zone? You need
Calendar cal = new GregorianCalendar(TimeZone.getTimeZone("Asia/Tokyo"))
cal.set(Calendar.HOUR_OF_DAY, 15) //15:00 in Tokyo
cal.set(Calendar.MONTH, Calendar.NOVEMBER)
cal.setTimeZone(TimeZone.getTimeZone("Australia/Melbourne"))
cal.get(Calendar.HOUR_OF_DAY) //17:00 in Melbourne
Note that after changing the time zone the date (point in time) didn't changed. Only the representation (current hour in this particular time zone). Also note that November is important there. If we change the month to July suddenly the hour in Melbourne changes to 16:00. That's because Tokyo does not observe DST, while Melbourne does.
There is another catch in Java with time zones. When you are trying to format a date you need to specify time zone explicitly:
DateFormat format = DateFormat.getTimeInstance
format.setTimeZone(TimeZone.getTimeZone("Europe/Moscow"))
Otherwise DateFormat
always uses current computer's time zone which is often inappropriate:
format.format(cal.getTime())
Since format()
method does not allow Calendar
instances (even though it accepts Object
as a parameter - sic!) you have to call Calendar.getTime()
- which returns Date
. And as being said previously - Date
instances are not aware of time zones, hence the Tokyo and Melbourne settings are lost.
You can try Joda-Time library. They have 2 functions called withZone() and withZoneRetainFields() to perform timezone calculations.