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

Viewed 7560

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?

3 Answers

Here is my code two calculate the time difference between two different timezones. like current timezone(GMT+05:00) and foreign timezone(GMT+05:30).

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                LocalDate today = LocalDate.now();
                Duration timeDifference = Duration.between(today.atStartOfDay(ZoneId.of(foreigntimezone)), today.atStartOfDay(ZoneId.of(currenttimezone)));
                holder.textViewTimeDifference.setText(timeDifference.toString());
            } else {
                long now = System.currentTimeMillis();
                long diffMilliSeconds = TimeZone.getTimeZone(gmtReplaceUTC).getOffset(now) - TimeZone.getTimeZone(currentTimeZone).getOffset(now);
                if (diffMilliSeconds > 0) {
                    String timeDifference = formatTime(diffMilliSeconds);
                    holder.textViewTimeDifference.setText(timeDifference);
                } else {
                    String timeDifference = formatTime(-diffMilliSeconds);
                    holder.textViewTimeDifference.setText("-" + timeDifference);
                }
            }
}

Result: for above 26 API level (PT+30M) and for below (30:00)

Related