Get the hours difference in Java
Description
The following code shows how to get the hours difference.
Example
//from www .j a v a 2 s .c o m
import java.util.Calendar;
import java.util.Date;
public class Main {
public final static long SECOND_MILLIS = 1000;
public final static long MINUTE_MILLIS = SECOND_MILLIS * 60;
public final static long HOUR_MILLIS = MINUTE_MILLIS * 60;
/**
* Get the hours difference
*/
public static int hoursDiff(Date earlierDate, Date laterDate) {
if (earlierDate == null || laterDate == null)
return 0;
return (int) ((laterDate.getTime() / HOUR_MILLIS) - (earlierDate.getTime() / HOUR_MILLIS));
}
public static void main(String[] argv) {
Date date1 = Calendar.getInstance().getTime();
Calendar cal = Calendar.getInstance();
cal.set(2010, 10, 10);
Date date2 = cal.getTime();
System.out.println(hoursDiff(date1, date2));
}
}
The code above generates the following result.