3

我正在尝试计算日期之间的时间差异:

public static void main(String args[])
{
    String start = "2013-03-10 10:28:47.000000";
    String end = "2013-04-07 09:54:08.054577";

    CalculateDuration calc = new CalculateDuration();
    calc.calculateDiffrenceInMinutes(start,end);
}
public int calculateDiffrenceInMinutes(String start_time, String end_time)
{

    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  

    Date d1 = null;
    Date d2 = null;
    try {
        d1 = format.parse(start_time);
        d2 = format.parse(end_time);
    } catch (ParseException e) {
        e.printStackTrace();
    }    

    // Get msec from each, and subtract.
    int diff = (int) d2.getTime() - (int)d1.getTime();
    int diffSeconds = (int) (diff / 1000);         
    int diffMinutes = (int) (diff / (60 * 1000));         
    int diffHours = (int) (diff / (60 * 60 * 1000));                      

    return diffMinutes;
}

出于某种原因,即使结束日期在开始日期之后,我也无法理解我展示的示例给出负输出。

有任何想法吗?

4

3 回答 3

8

尝试改变

int diff = (int) d2.getTime() - (int)d1.getTime();

long diff = d2.getTime() - d1.getTime();

显式类型转换 from longtoint将导致精度损失,并可能导致减法为负值。

long a = 90000000000000L;
long b = 10000001000000L;

a>b
(int)a-(int)b => negative value
于 2013-09-02T14:02:15.267 回答
4

正如其他人指出的精度损失,您可以在此处阅读详细信息。

long diff = d2.getTime() - d1.getTime();
long diffSeconds = diff / 1000 % 60;  
long diffMinutes = diff / (60 * 1000) % 60;
long diffHours   = diff / (60 * 60 * 1000) % 60;

Java 的日期时间 API 存在一些设计问题。日历不是线程安全的。你可能想看看Joda-Time。这将使它变得如此简单-

Seconds.between(startDate, endDate);
于 2013-09-02T14:27:30.193 回答
2

Date#getTime()返回 along并且这是有原因的。因为自1970 年 1 月 1 日 00:00:00 GMT以来已经过去了好几毫秒。Anint无法容纳这么大的数字(并且溢出,这解释了为什么您可能会得到负数(取决于两个日期))。所以你应该用long它来做计算。

我会像这样更改您的代码:

long diff = d2.getTime() - d1.getTime();
long diffSeconds = diff / (          1000);         
long diffMinutes = diff / (     60 * 1000);         
long diffHours   = diff / (60 * 60 * 1000);

当然,您还需要将calculateDiffrenceInMinutes方法的返回类型更改为long.

注意:在您的示例中,您也可以离开diffSeconds,diffMinutesdiffHoursas int。但我不建议这样做,因为如果日期相距太远,这将是一个失败的解决方案。

于 2013-09-02T14:06:21.627 回答