Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
528 views
in Technique[技术] by (71.8m points)

android timezone difference is 1 hour less then expected

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;
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...