DateDiff is an useful java class to calculate difference between two java.util.Date and getting the result represented by days, hours, minutes. See the code above:
import java.util.Date; import java.util.Calendar; import java.util.Locale; public class DateDiff {
private Date d1; private Date d2; private final int MSEC_PER_SECOND = 1000; private final int MSEC_PER_MINUTE = 60*1000; private final int MSEC_PER_HOUR = 60*60*1000; private final int MSEC_PER_DAY = 24*60*60*1000; private long days; private long hours; private long minutes; private long seconds; public DateDiff() { d1 = new Date(); d2 = new Date(); compute(); } public DateDiff(Date d1, Date d2) { this.d1 = d1; this.d2 = d2; compute(); }
/* GETTERS AND SETTERS METHODS */ public Date getD1() { return d1; }
public void setD1(Date d1) { this.d1 = d1; compute(); }
public Date getD2() { return d2; }
public void setD2(Date d2) { this.d2 = d2; compute(); } public long getDays() { return days; }
public long getHours() { return hours; }
public long getMinutes() { return minutes; }
public long getSeconds() { return seconds; } /* BUSINESS METHODS */ public long getDiffInMillisecs() { return d2.getTime() - d1.getTime(); }
public long getDiffInSeconds() { return ( d2.getTime() - d1.getTime()) / MSEC_PER_SECOND; }
public long getDiffInMinutes() { return ( d2.getTime() - d1.getTime()) / MSEC_PER_MINUTE; } public long getDiffInHours() { return ( d2.getTime() - d1.getTime()) / MSEC_PER_HOUR; }
public long getDiffInDays() { return ( d2.getTime() - d1.getTime()) / MSEC_PER_DAY; } private void compute() { days = getDiffInDays(); hours = getDiffInHours() - (getDiffInDays() * 24); minutes = getDiffInMinutes() - (getDiffInHours() * 60); seconds = getDiffInSeconds() - (getDiffInMinutes() * 60); } public String toString () { return days+" days, "+hours+" hours, "+minutes+" minutes, "+seconds+" seconds "; } public int getWorkingDays() { Calendar c = Calendar.getInstance(); c.setTime(d1); int counter = 0; for ( ; !c.getTime().after(d2) ; c.add(Calendar.DATE, 1) ) { if (c.get(Calendar.DAY_OF_WEEK)!=Calendar.SATURDAY && c.get(Calendar.DAY_OF_WEEK)!=Calendar.SUNDAY ) counter++; } return counter; }
|
------------------------------------------------------------------------------------------
EXAMPLE OF USAGE:
import java.util.Date;
public class Test {
public static void main (String args[]) {
Date d1 = new Date(2008, 10, 1, 10, 30, 00); // 06/10/2008 10:30:00
Date d2 = new Date(2008, 10, 10, 11, 10, 20); // 22/10/2008 11:10:20
DateDiff diff = new DateDiff( d1 , d2 );
System.out.println(diff);
}
}