Jacob said:
I use the Day class (
http://geosoft.no/software/day/Day.java.html)
as follows:
Day day1 = new Day (1901, 2, 3);
Day day2 = new Day (2028, 4, 2);
Day day3 = new Day (2028, 4, 3);
System.out.println (day1.daysBetween (day2));
System.out.println (day1.daysBetween (day3));
Hi Jacob,
Thank you very much for crediting me in your code at geosoft.no, but
you didn't read my article close enough or maybe you just run
into the same problems as I did. You still have a bug.
I tried your difference method and it is incorrect 'half' [
]
the time. If you run the following code through a Daylight spring
forward date hence a 23 hour day you will see the problem.
Running the following results in:
Cal1 date is in daylight savings = false
diff is 0 in DLS false
diff is 1 in DLS false
diff is 2 in DLS false
diff is 3 in DLS false <--- same answer
diff is 3 in DLS true <--- for 2 diff. midnights
diff is 4 in DLS true
diff is 5 in DLS true
Note the diff stays at 3 for the midnight before and the
midnight after the Spring forward and then remains off
by one.
You can use the kludge where you add an hour because
you are always setting the underlying calendar at
midnight.
NOTE TO OTHERS, DO NOT JUST ADD ONE HOUR TO THE CALCULATION
WHEN SUBTRACTING ARBITRARY TIMES. Why? Because from
for example:
12:30 AM the morning before the DLS fall back day to
12:29 AM mornings (47:59 hours) later should
result in a value of 1 (it is more than 24 hours later, but less
than 48 hours later, but adding 1 hour results in a value
of 3.
-Paul
-Paul
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.TimeZone;
/**
* @author Paul Hill
* @since 2005-01-05
*/
public class Scratch {
/**
* Return number of days between two days.
* The method always returns a positive number of days.
*
* @param date The day to compare to.
* @return Number of days between this and day.
*/
public static int daysBetween (Calendar cal1, Calendar cal2) {
long millisBetween = Math.abs (cal2.getTime().getTime() -
cal1.getTime().getTime());
return (int) Math.round (millisBetween / (1000 * 60 * 60 * 24));
}
public static void main(String args[]) {
Calendar cal1 = new GregorianCalendar( 2004, Calendar.APRIL, 1 );
Calendar cal2 = new GregorianCalendar( 2004, Calendar.APRIL, 1 );
TimeZone tz = cal1.getTimeZone();
System.out.println( "Cal1 date is in daylight savings = " +
tz.inDaylightTime( cal1.getTime() ));
for ( int i = 0; i < 7; i++ ) {
System.out.println( "diff is " + daysBetween( cal1, cal2 ) +
"\t in DLS " + tz.inDaylightTime( cal2.getTime() ) );
cal2.add( Calendar.DATE, 1);
}
}
}