问题

这个问题在这里已有答案:

  • 如何在Java中将毫秒转换为"X分钟,x秒"? 24个答案

我想计算2个日期in小时/分钟/秒之间的差异。

我的代码在这里有一个小问题:

String dateStart = "11/03/14 09:29:58";
String dateStop = "11/03/14 09:33:43";

// Custom date format
SimpleDateFormat format = new SimpleDateFormat("yy/MM/dd HH:mm:ss");  

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

// Get msec from each, and subtract.
long diff = d2.getTime() - d1.getTime();
long diffSeconds = diff / 1000;         
long diffMinutes = diff / (60 * 1000);         
long diffHours = diff / (60 * 60 * 1000);                      
System.out.println("Time in seconds: " + diffSeconds + " seconds.");         
System.out.println("Time in minutes: " + diffMinutes + " minutes.");         
System.out.println("Time in hours: " + diffHours + " hours.");

这应该产生:

Time in seconds: 45 seconds.
Time in minutes: 3 minutes.
Time in hours: 0 hours.

但是我得到了这个结果:

Time in seconds: 225 seconds.
Time in minutes: 3 minutes.
Time in hours: 0 hours.

谁能看到我在这里做错了什么?


#1 热门回答(203 赞)

我更愿意使用suggestjava.util.concurrent.TimeUnitclass。

long diff = d2.getTime() - d1.getTime();//as given

long seconds = TimeUnit.MILLISECONDS.toSeconds(diff);
long minutes = TimeUnit.MILLISECONDS.toMinutes(diff);

#2 热门回答(87 赞)

尝试

long diffSeconds = diff / 1000 % 60;  
long diffMinutes = diff / (60 * 1000) % 60;

#3 热门回答(38 赞)

如果你能够使用外部库,我建议你使用Joda-Time,注意:

Joda-Time是Java SE 8之前Java的事实标准日期和时间库。现在要求用户迁移到java.time(JSR-310)。

计算之间的示例:

Seconds.between(startDate, endDate);
Days.between(startDate, endDate);

原文链接