Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate date/time difference in java [duplicate]

Tags:

java

time

People also ask

How do you calculate the difference between two dates in Java?

getTime() – d1. getTime(). Use date-time mathematical formula to find the difference between two dates. It returns the years, days, hours, minutes, and seconds between the two specifies dates.

How do you calculate timestamp difference?

Discussion: If you'd like to calculate the difference between the timestamps in seconds, multiply the decimal difference in days by the number of seconds in a day, which equals 24 * 60 * 60 = 86400 , or the product of the number of hours in a day, the number of minutes in an hour, and the number of seconds in a minute.


I would prefer to use suggested java.util.concurrent.TimeUnit class.

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

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

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.


If you are able to use external libraries I would recommend you to use Joda-Time, noting that:

Joda-Time is the de facto standard date and time library for Java prior to Java SE 8. Users are now asked to migrate to java.time (JSR-310).

Example for between calculation:

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

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.


Try this for a friendly representation of time differences (in milliseconds):

String friendlyTimeDiff(long timeDifferenceMilliseconds) {
    long diffSeconds = timeDifferenceMilliseconds / 1000;
    long diffMinutes = timeDifferenceMilliseconds / (60 * 1000);
    long diffHours = timeDifferenceMilliseconds / (60 * 60 * 1000);
    long diffDays = timeDifferenceMilliseconds / (60 * 60 * 1000 * 24);
    long diffWeeks = timeDifferenceMilliseconds / (60 * 60 * 1000 * 24 * 7);
    long diffMonths = (long) (timeDifferenceMilliseconds / (60 * 60 * 1000 * 24 * 30.41666666));
    long diffYears = timeDifferenceMilliseconds / ((long)60 * 60 * 1000 * 24 * 365);

    if (diffSeconds < 1) {
        return "less than a second";
    } else if (diffMinutes < 1) {
        return diffSeconds + " seconds";
    } else if (diffHours < 1) {
        return diffMinutes + " minutes";
    } else if (diffDays < 1) {
        return diffHours + " hours";
    } else if (diffWeeks < 1) {
        return diffDays + " days";
    } else if (diffMonths < 1) {
        return diffWeeks + " weeks";
    } else if (diffYears < 1) {
        return diffMonths + " months";
    } else {
        return diffYears + " years";
    }
}

This is more of a maths problem than a java problem basically.

The result you receive is correct. This because 225 seconds is 3 minutes (when doing an integral division). What you want is the this:

  • divide by 1000 to get the number of seconds -> rest is milliseconds
  • divide that by 60 to get number of minutes -> rest are seconds
  • divide that by 60 to get number of hours -> rest are minutes

or in java:

int millis = diff % 1000;
diff/=1000;
int seconds = diff % 60;
diff/=60;
int minutes = diff % 60;
diff/=60;
hours = diff;

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