Java - Calendar / Date difference - Find differenc

2019-09-03 03:34发布

问题:

Trying to make a little Countdown program in Java.

I am working on the finding the difference between the dates part of the app, and for some reason I am only getting the days.

I want the days, hours, minutes, and seconds. I am not sure why my calculation is just being rounded to an even integer... 163 in this example, and not 163.xx?

Here is my code:

import java.util.Date;
import java.util.Calendar;
import java.util.GregorianCalendar;

public class CalcData {

    Calendar cal1;
    Date today;

    public CalcData() {

        cal1 = new GregorianCalendar();
        today = new GregorianCalendar().getTime();

    }

    public String calcDiff() {

        cal1.set(2013, 6, 27, 7, 15, 0);
        double theDays = calcDays(cal1.getTime(), today);
        return "" + theDays;

    }

    public double calcDays(Date d1, Date d2) {

        double theCalcDays = (double) ((d1.getTime() - d2.getTime()) / (1000 * 60 * 60 * 24));
        return theCalcDays;

    }
}

When I run this, as I said, I get the result: 163.0

I would think, if it is using milliseconds, that it would be some sort of decimal. I am sure it is something simple that I am missing, but just can't find it!

Thanks in advance!

回答1:

You are dividing an integer by another integer. You need to cast those to doubles before you do the division. Like this

double theCalcDays = ((double) (d1.getTime() - d2.getTime())) / (1000 * 60 * 60 * 24);