Monday, August 2, 2010

Determine the Time Difference Between Two Timezones in Java

To calculate the time difference between two different timezones, we can use a java.util.Calendar class to get the current time at a given timezone, including the local timezone. The difference in hours can then be calculated by subtracting the hour of day of two Calendar instances. Looking at the day of month allows you to correct for the case when the current time spans two days by adding 24.


import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.TimeZone;

// Java 1.4+ Compatible
//
//The following example code demonstrates how to calculate
//the time difference between two different timezones, in
// particular New York and Alaska, given the current time.
// Since daylight savings time effective dates are different
// between countries, it's important to calculate the
// timezone difference at a particular date. Calculating
// the difference between the local timezone and a different
// one is also demonstrated.
// and a different one is also demonstrated.

public class DifferenceBetweenTwoTimezones {

public static void main(String[] args) {

// East Coast Time
Calendar c = new GregorianCalendar(TimeZone.getTimeZone("America/New_York"));
c.setTimeInMillis(new Date().getTime());
int EastCoastHourOfDay = c.get(Calendar.HOUR_OF_DAY);
int EastCoastDayOfMonth = c.get(Calendar.DAY_OF_MONTH);

// Alaska
c = new GregorianCalendar(TimeZone.getTimeZone("America/Anchorage"));
c.setTimeInMillis(new Date().getTime());
int AlaskaHourOfDay = c.get(Calendar.HOUR_OF_DAY);
int AlaskaDayOfMonth = c.get(Calendar.DAY_OF_MONTH);

// Difference between New York and Alaska
int hourDifference = EastCoastHourOfDay - AlaskaHourOfDay;
int dayDifference = EastCoastDayOfMonth - AlaskaDayOfMonth;
if (dayDifference != 0) {
hourDifference = hourDifference + 24;
}
System.out.println(hourDifference);

// Local Time
int localHourOfDay = Calendar.getInstance().get(Calendar.HOUR_OF_DAY);
int localDayOfMonth = Calendar.getInstance().get(Calendar.DAY_OF_MONTH);

// Difference between New York and Local Time (for me Germany)
hourDifference = EastCoastHourOfDay - localHourOfDay;
dayDifference = EastCoastDayOfMonth - localDayOfMonth;
if (dayDifference != 0) {
hourDifference = hourDifference + 24;
}
System.out.println(hourDifference);

}

}




Here is the output of the example code:
4
-6

See also: Get All Timezones Available in the TimeZone Class in Java

1 comment:

Anonymous said...

day diffs does not mean a diff of 24 hrs