Android how to get time difference between two time zones in android?

你。 提交于 2019-12-18 15:36:10

问题


I need to get time difference between two dates in different time zones. Currently I am doing this:

Calendar c1=Calendar.getInstance(TimeZone.getTimeZone("EDT"));
Calendar c2=Calendar.getInstance(TimeZone.getTimeZone("GMT"));
String diff=((c2.getTimeInMillis()-c1.getTimeInMillis())/(1000*60*60))+" hours";
new AlertDialog.Builder(this).setMessage(diff).create().show();

I get 0 hours. What am I doing wrong?


回答1:


getTimeInMillis() returns the number of milliseconds since the epoch in UTC. In other words, the time zone is irrelevant to it.

I suspect you actually want:

long currentTime = System.currentTimeMillis();
int edtOffset = TimeZone.getTimeZone("EDT").getOffset(currentTime);
int gmtOffset = TimeZone.getTimeZone("GMT").getOffset(currentTime);
int hourDifference = (gmtOffset - edtOffset) / (1000 * 60 * 60);
String diff = hourDifference + " hours";



回答2:


Jon is close, but due to character restrictions I can't edit his answer. This is the same code but with "EDT" changed to "EST" for Eastern Standard Time.

long currentTime = System.currentTimeMillis();
int edtOffset = TimeZone.getTimeZone("EST").getOffset(currentTime);
int gmtOffset = TimeZone.getTimeZone("GMT").getOffset(currentTime);
int hourDifference = (gmtOffset - edtOffset) / (1000 * 60 * 60);
String diff = hourDifference + " hours";

But this solution makes a major assumption that TimeZone.getAvailableIDs() has within it's string array both "EST" and "GMT". If that method doesn't contain those timezone strings it will come back as 0 offset.



来源:https://stackoverflow.com/questions/6760031/android-how-to-get-time-difference-between-two-time-zones-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!