What I need is a time difference between specific timezone ("Russia/Moscow") and local time of the user, difference should be in hours.
I run into problem that the Difference of Time Zones is sometimes false calculated. I calculate difference (in hours) between local offset to UTC of android device and remote offset to UTC. For most user it is fine.. but many user are complaining about the problem.. I am not able to reproduce it at my phone or emulators. The "wrong" displayed time difference is all ways 1 hour less. In Moscow it is 15:00, in Europe 12:00. But the user see the offset of 2 hours here is my code.
String tz="Europe/Moscow"
Calendar mCalendar = new GregorianCalendar();
mCalendar.setTimeZone( TimeZone.getTimeZone(tz));
TimeZone mTimeZone = mCalendar.getTimeZone();
int remote = mTimeZone.getRawOffset()/1000/60/60;
Calendar mCalendar2 = new GregorianCalendar();
TimeZone mTimeZone2 = mCalendar2.getTimeZone();
int local = mTimeZone2.getRawOffset()/1000/60/60;
return local - remote;
You are making the common mistake of equating a Time Zone with a Time Zone Offset. They are two different things. Please read the timezone tag wiki.
When you call
getRawOffset
, that returns the standard offset for that time zone. To get the offset that's in effect at a particular point in time, you can usegetOffset
, which takes a parameter of the timestamp for the point in time you are talking about.Consider the following code, which returns the difference that is currently in effect:
Note a couple of things:
Calendar
class.double
, notint
. For example, tryAsia/Kolkata
, which uses UTC+5:30 the whole year, orAustralia/Adelaide
, which alternates between UTC+9:30 and UTC+10:30.Consider also using Joda-Time, which is a much more robust way of working with time in Java.