开发者

java date difference puzzle

I am trying to calculate a date time difference but I'm getting 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 = C开发者_Go百科alendar.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 this be? What is the remedy?

Thanks,

Elliott


If you're setting ccal like so "ccal.set(2011, 1, 31)" the date is actually March 3, 2001, since months are zero based and the calendar rolls by default. So the difference of 48hrs (96-48) is correct because there are two days between March 1 (set(2011,2,1)) and March 3 (set(2011,1,31)).


You know that months are 0 based, right? So that 0 represents January and 1 represents February, so that 1 31 2011 doesn't exist. In fact it is better not to use numbers at all but instead to use the Calendar constants for the months, i.e.: Calendar.JANUARY. To see for yourself what's happening, print out your Calendar's respective Date:

  ccal.set(2011, 1, 31);
  System.out.println(ccal.getTime());
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜