Java - Calendar / Date difference - Find difference down to seconds

眉间皱痕 提交于 2019-12-25 07:26:37

问题


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);


来源:https://stackoverflow.com/questions/14869742/java-calendar-date-difference-find-difference-down-to-seconds

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!