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 use getOffset
, 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:
long now = System.currentTimeMillis();
String tz = "Europe/Moscow";
TimeZone mTimeZone = TimeZone.getTimeZone(tz);
int remote = mTimeZone.getOffset(now);
TimeZone mTimeZone2 = TimeZone.getDefault();
int local = mTimeZone2.getOffset(now);
double differenceInHours = (local - remote) / 3600000.0;
return differenceInHours;
Note a couple of things:
- I did not need a
Calendar
class.
- The offsets are both for the same "now". You will get different results depending on when you run it.
- Not all offsets use a whole number of hours, so this function should return
double
, not int
. For example, try Asia/Kolkata
, which uses UTC+5:30 the whole year, or Australia/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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…