Java date difference puzzle

I am trying to calculate the time difference, but I get some strange results: Here is the source:

import java.util.Calendar; import java.util.Collections; import java.util.Vector; public class Main { static Calendar dcal = Calendar.getInstance(); static Calendar ccal = Calendar.getInstance(); public static void main(String[] args) { dcal.set(2011, 1, 27); ccal.set(2011,2,1); long dtime = dcal.getTimeInMillis(); long ctime = ccal.getTimeInMillis(); long diff = ctime - dtime; int hours = (int) (diff / (1000 * 60 * 60)); System.out.println("hours->"+hours); } } 

When I set ccal to 1 31 2011, the date difference is 96 hours, but when I set it to 2 1 2011 the date difference is 48 hours. How can it be? What remedy?

Thanks,

Elliot

+6
java time
source share
2 answers

If you set ccal as " ccal.set(2011, 1, 31) ", the date is actually March 3, 2001, since the months are based on the zero value and the default calendar. Thus, the 48-hour difference (96-48) is correct since there are two days between March 1 ( set(2011,2,1) ) and March 3 ( set(2011,1,31) ).

+6
source share

You know that months are based on 0, right? So 0 represents January and 1 represents February, so 1 31 2011 does not exist. In fact, it’s better not to use numbers at all, but instead to use calendar constants for months, i.e.: Calendar.JANUARY. To find out what is going on, print your corresponding date on the calendar:

  ccal.set(2011, 1, 31); System.out.println(ccal.getTime()); 
+4
source share

All Articles