Java - 日历/日期差异 - 查找差异到秒 [英] Java - Calendar / Date difference - Find difference down to seconds

查看:122
本文介绍了Java - 日历/日期差异 - 查找差异到秒的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试用Java制作一个小计数倒计时程序。

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.

我想要天,小时,分钟和秒。我不知道为什么我的计算只是四舍五入到一个整数... 163在这个例子,而不是163.xx?

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?

这里是我的代码: / p>

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;

    }
}

说,我得到的结果:163.0

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!

提前感谢!

推荐答案

您正在将整数除以另一个整数。你需要在你做分区之前把它们投射到双打。像这样

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

这篇关于Java - 日历/日期差异 - 查找差异到秒的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆