Java date difference puzzle

I want to calculate a date time difference, but I get some strange results:

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 January 31, 2011, the date difference is 96 hours, but when I set it to February 1, 2011, the date difference is 48 hours How did this happen? What are remedies?

thank you,

Elliot

Solution

If you're like CCAL If CCAL is set as set (2011,31), the date is actually March 3, 2001, because the months are based on zero and the calendar scrolls by default Therefore, the difference of 48 hours (96-48) is correct, because there are two days between March 1 (set (2011,1)) and March 3 (set (2011,31))

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>