Calculate date/time difference in java [duplicate]

2018-12-31 08:02发布

This question already has an answer here:

I want to calculate difference between 2 dates in hours/minutes/seconds.

I have a slight problem with my code here it is :

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

This should produce :

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

However I get this result :

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

Can anyone see what I'm doing wrong here ?

标签: java time
17条回答
初与友歌
2楼-- · 2018-12-31 08:48

Since Java 5, you can use java.util.concurrent.TimeUnit to avoid the use of Magic Numbers like 1000 and 60 in your code.

By the way, you should take care to leap seconds in your computation: the last minute of a year may have an additional leap second so it indeed lasts 61 seconds instead of expected 60 seconds. The ISO specification even plan for possibly 61 seconds. You can find detail in java.util.Date javadoc.

查看更多
公子世无双
3楼-- · 2018-12-31 08:48

Here is a suggestion, using TimeUnit, to obtain each time part and format them.

private static String formatDuration(long duration) {
    long hours = TimeUnit.MILLISECONDS.toHours(duration);
    long minutes = TimeUnit.MILLISECONDS.toMinutes(duration) % 60;
    long seconds = TimeUnit.MILLISECONDS.toSeconds(duration) % 60;
    long milliseconds = duration % 1000;
    return String.format("%02d:%02d:%02d,%03d", hours, minutes, seconds, milliseconds);
}

SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss,SSS");
Date startTime = sdf.parse("01:00:22,427");
Date now = sdf.parse("02:06:38,355");
long duration = now.getTime() - startTime.getTime();
System.out.println(formatDuration(duration));

The result is: 01:06:15,928

查看更多
倾城一夜雪
4楼-- · 2018-12-31 08:48

As said before - think this is a good answer

/**
 * @param d2 the later date 
 * @param d1 the earlier date
 * @param timeUnit - Example Calendar.HOUR_OF_DAY
 * @return
 */
public static int getTimeDifference(Date d2,Date d1, int timeUnit) {
     Date diff = new Date(d2.getTime() - d1.getTime());

     Calendar calendar = Calendar.getInstance();
     calendar.setTime(diff);
     int hours = calendar.get(Calendar.HOUR_OF_DAY);
     int minutes = calendar.get(Calendar.MINUTE);
     int seconds = calendar.get(Calendar.SECOND);
     if(timeUnit==Calendar.HOUR_OF_DAY)
         return hours;
     if(timeUnit==Calendar.MINUTE)
         return minutes;
     return seconds;
 }
查看更多
素衣白纱
5楼-- · 2018-12-31 08:49
Date startTime = new Date();
//...
//... lengthy jobs
//...
Date endTime = new Date();
long diff = endTime.getTime() - startTime.getTime();
String hrDateText = DurationFormatUtils.formatDuration(diff, "d 'day(s)' H 'hour(s)' m 'minute(s)' s 'second(s)' ");
System.out.println("Duration : " + hrDateText);


You can use Apache Commons Duration Format Utils. It formats like SimpleDateFormatter

Output:

0 days(s) 0 hour(s) 0 minute(s) 1 second(s)

查看更多
泪湿衣
6楼-- · 2018-12-31 08:56

try

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

NOTE: this assumes that diff is non-negative.

查看更多
登录 后发表回答