import java.util.*;
public class TestDate {
public static void main(String args[]){
/*
ex .
java TestDate 1999 0 1 1999 8 1
to get days between 1999-01-01 and 1999-09-01
(remember months are zero-based...)
*/
TestDate a = new TestDate(args);
}
TestDate(String args[]) {
Calendar c1 = new GregorianCalendar();;
Calendar c2 = new GregorianCalendar();;
// need more error checking here...
c1.set(Integer.parseInt(args[0]),
Integer.parseInt(args[1]) ,
Integer.parseInt(args[2]), 0, 0, 0);
c2.set(Integer.parseInt(args[3]),
Integer.parseInt(args[4]) ,
Integer.parseInt(args[5]), 0, 0, 0);
System.out.println
(daysBetween(c1.getTime(),c2.getTime()) +
" day(s) between " + args[0] + "-" + args[1] + "-" + args[2] +
" and " + args[3] + "-" + args[4] + "-" + args[5]);
}
static final long ONE_HOUR = 60 * 60 * 1000L;
public long daysBetween(Date d1, Date d2){
return ( (d2.getTime() - d1.getTime() + ONE_HOUR) /
(ONE_HOUR * 24));
}
}The "right" way would be to compute the julian day number of both dates and then do the substraction. See this HowTo. Thanks to P. Hill for the tip.
Written and compiled by Réal Gagnon ©1998-2005
[ home ]