How to Calculate a Time Difference in Java

How can I calculate a time difference in Java?

String time1 = "16:00:00";
String time2 = "19:00:00";

SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");
Date date1 = format.parse(time1);
Date date2 = format.parse(time2);
long difference = date2.getTime() - date1.getTime();

Difference is in milliseconds.

I modified sfaizs post.

Calculate date/time difference in java

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.

Java - Time difference in minutes

This is not working because when you create a new date with just a time in it, it's assuming the day is "today".

What you could do is:

// This example works
String dateStart = "2045";
String dateStop = "2300";

// This example doesnt work
//String dateStart = "2330";
//String dateStop = "0245";

// Custom date format
SimpleDateFormat format = new SimpleDateFormat("HHmm");

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

// MY ADDITION TO YOUR CODE STARTS HERE
if(d2.before(d1)){
Calendar c = Calendar.getInstance();
c.setTime(d2);
c.add(Calendar.DATE, 1);
d2 = c.getTime();
}
// ENDS HERE

long diff = d2.getTime() - d1.getTime();
long minutes = TimeUnit.MILLISECONDS.toMinutes(diff);
System.out.println("Time in minutes: " + minutes + " minutes.");

But you should consider using Java 8 new Date/Time features, or Joda Time.

Calculating the difference between two Java date instances

The JDK Date API is horribly broken unfortunately. I recommend using Joda Time library.

Joda Time has a concept of time Interval:

Interval interval = new Interval(oldTime, new Instant());

EDIT: By the way, Joda has two concepts: Interval for representing an interval of time between two time instants (represent time between 8am and 10am), and a Duration that represents a length of time without the actual time boundaries (e.g. represent two hours!)

If you only care about time comparisions, most Date implementations (including the JDK one) implements Comparable interface which allows you to use the Comparable.compareTo()

How to calculate the time difference between two events in Java?

You can use System.currentTimeMillis() to save the current time at one millisecond resolution.
Just save the time whenever the first event occurs (better use a long var to hold that value)
and again when the 2nd event occurs. The difference divided by 1000 will give you time difference in seconds.

Time difference in AM/PM in Java

The new java.time methods LocalTime, DateTimeFormatter and Duration provide much better methods for handling this. For example:

DateTimeFormatter format = DateTimeFormatter.ofPattern("h:m:s a");

LocalTime time1 = LocalTime.parse("12:00:00 am", format);
LocalTime time2 = LocalTime.parse("2:00:20 pm", format);

Duration dur = Duration.between(time1, time2);

System.out.println(dur.toMinutes() + " minutes " + dur.toSecondsPart() + " seconds");

Note: Duration.toSecondsPart requires Java 9 or later, the rest of this code requires Java 8 or later.

calculate time difference between two hours in timeformat hh:mm:ss java

The answer by Michael is good (+1). Allow me to add that you don’t need to mention any formatter (though I also see the advantage of being explicit about the format) and you don’t need to invent an artificial and probably incorrect date to deal with the 24:00 issue.

        LocalTime start = LocalTime.parse(timeStart);
LocalTime stop = LocalTime.parse(timeStop);
if (stop.isAfter(start)) { // the normal situation
System.out.println(formatDuration(Duration.between(start, stop)));
} else if (stop.equals(LocalTime.MIDNIGHT)) {
System.out.println(
formatDuration(Duration.between(start, stop).plusDays(1)));
} else {
System.out.println("End time " + timeStop + " was before start time " + timeStart);
}

I am assuming that the times are on the same date except that an end time of 00:00:00 would mean midnight at the end of the day (sometimes called 24.00 where I come from). If you need to calculate, say from 13:00 one day to 13:00 to the next day as 24 hours, just delete the second if condition and the last else block.

Feeding your example input gives the output you asked for:

04:57:15
01:00:00
12:05:00
11:55:00

As Michael mentions, the toMinutesPart and toSecondsPart methods were introduced in Java 9. For how to format the duration in earlier Java versions see my answer here.

What went wrong in your code?

To parse times on a 24 hour clock correctly (12:05:00, 13:00:00, 14:00:00, 15:00:58) you need to use uppercase HH for hour of day. Lowercase hh is for hour within AM or PM from 01 to 12 inclusive. When you don’t specify AM or PM, AM is used as default. So 10:03:43 is parsed as you expected. Funnily 15:00:58 is too even though there is no 15:00:58 AM. SimpleDateFormat just extrapolates. The trouble comes with 12:05:00 since 12:05:00 AM means 00:05:00. On my computer I got 23:55:00 (not 00:05:00, as you said you got). This is because you had first altered the start time into 24:00:00 and next calculated the time from 00:05:00 to 24:00:00, which is 23:55:00. Since you know which time is the start time and which is the end time, you probably shouldn’t swap them in the case where they seem to be in the wrong order. In your last example I got 23:55:00 too. What happens is the same except the times aren’t swapped since 00:05:00 is already before 24:00:00.

Calculating the time difference between two times in Java

First, I am assuming that the calculation takes place in a time zone without summer time (DST) and other anomalies, or at least on dates where there is no transition.

I left out the reading from the BufferedReader since you already seem to be handling this fine.

    String time1 = "23:05:38";
LocalTime t1 = LocalTime.parse(time1);
String time2 = "12:36:07";
LocalTime t2 = LocalTime.parse(time2);
Duration diff = Duration.between(t2, t1);
System.out.println(diff.toHours());

This prints the expected

10

As you can see, I am following Deb’s suggestion in the comment: using the modern Java date and timeAPI known as JSR-310 or java.time. This automatically solves your problem since LocalTime parses your times on the 24 hour clock without any explicit formatter and therefore without the opportunity to use the wrong case in a format pattern string.

That’s right, I agree with d.j.brown that the lowercase hh in your pattern is the culprit. Your times were interpreted as 23:05:38 AM, which is nonsense, but the outdated SimpleDateFormat just takes that to mean 11:05:38 PM, that is 23:05:38 on a 24 hour clock, that is what you had expected. IMHO it’s quite nasty to let you get away with such a bug without telling you. You were fortunate to have a time that started with “12”, for 12:36:07 AM means 0:36:07 on a 24 hour clock, so this time you got a wrong result and were made aware something was wrong. Otherwise your bug would have gone unnoticed, maybe for a long time. This long story to carry a morale: stay far away from SimpleDateFormat.

Question: Can I use the modern API with my Java version?

If using at least Java 6, you can.

  • In Java 8 and later the new API comes built-in.
  • In Java 6 and 7 get the ThreeTen Backport, the backport of the new classes (that’s ThreeTen for JSR-310, where the modern API was first defined).
  • On Android, use the Android edition of ThreeTen Backport. It’s called ThreeTenABP, and I think that there’s a wonderful explanation in this question: How to use ThreeTenABP in Android Project.

How to find the duration of difference between two dates in java?

try the following

{
Date dt2 = new DateAndTime().getCurrentDateTime();

long diff = dt2.getTime() - dt1.getTime();
long diffSeconds = diff / 1000 % 60;
long diffMinutes = diff / (60 * 1000) % 60;
long diffHours = diff / (60 * 60 * 1000);
int diffInDays = (int) ((dt2.getTime() - dt1.getTime()) / (1000 * 60 * 60 * 24));

if (diffInDays > 1) {
System.err.println("Difference in number of days (2) : " + diffInDays);
return false;
} else if (diffHours > 24) {

System.err.println(">24");
return false;
} else if ((diffHours == 24) && (diffMinutes >= 1)) {
System.err.println("minutes");
return false;
}
return true;
}


Related Topics



Leave a reply



Submit