How to Find the Duration of Difference Between Two Dates in Java

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 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;
}

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.

Need to find the difference between two dates in days and hours form

You've already calculated the days and hours. All you need to do is print something like this:

System.out.println(days + " days " + (hours % 24) + " hours");

In case you haven't seen it before, % is the modulus operator. It gives you the remainder after division.

Calculate the difference between two dates in hours:minutes:seconds?

Try this function:-

//1 minute = 60 seconds
//1 hour = 60 x 60 = 3600
//1 day = 3600 x 24 = 86400
public void printDifference(Date startDate, Date endDate){

//milliseconds
long different = endDate.getTime() - startDate.getTime();

System.out.println("startDate : " + startDate);
System.out.println("endDate : "+ endDate);
System.out.println("different : " + different);

long secondsInMilli = 1000;
long minutesInMilli = secondsInMilli * 60;
long hoursInMilli = minutesInMilli * 60;
long daysInMilli = hoursInMilli * 24;

//long elapsedDays = different / daysInMilli;
//different = different % daysInMilli;

long elapsedHours = different / hoursInMilli;
different = different % hoursInMilli;

long elapsedMinutes = different / minutesInMilli;
different = different % minutesInMilli;

long elapsedSeconds = different / secondsInMilli;

System.out.printf(
"%d hours, %d minutes, %d seconds%n",
elapsedHours, elapsedMinutes, elapsedSeconds);

}

Java 8 calculate months between two dates

Since you don't care about the days in your case. You only want the number of month between two dates, use the documentation of the period to adapt the dates, it used the days as explain by Jacob. Simply set the days of both instance to the same value (the first day of the month)

Period diff = Period.between(
LocalDate.parse("2016-08-31").withDayOfMonth(1),
LocalDate.parse("2016-11-30").withDayOfMonth(1));
System.out.println(diff); //P3M

Same with the other solution :

long monthsBetween = ChronoUnit.MONTHS.between(
LocalDate.parse("2016-08-31").withDayOfMonth(1),
LocalDate.parse("2016-11-30").withDayOfMonth(1));
System.out.println(monthsBetween); //3

Edit from @Olivier Grégoire comment:

Instead of using a LocalDate and set the day to the first of the month, we can use YearMonth that doesn't use the unit of days.

long monthsBetween = ChronoUnit.MONTHS.between(
YearMonth.from(LocalDate.parse("2016-08-31")),
YearMonth.from(LocalDate.parse("2016-11-30"))
)
System.out.println(monthsBetween); //3

Difference between two DateTime objects in minutes

LocalDateTime fromdate = LocalDateTime.of(orderYear,orderMonth,orderDay,orderHour,orderMinute,orderSeconds);
LocalDateTime todate = LocalDateTime.of(deliverYear, deliverMonth, deliverDay,deliverHour,deliverMinute,deliverSeconds);
Duration difference = Duration.between(fromdate, todate);


Then you can format it using something similar to...

long hours = difference.toHours();
long mins = difference.minusHours(hours).toMinutes();

// Or if you're lucky enough to be using Java 9+
//String formatted = String.format("%dhrs %02dmins", duration.toHours(), duration.toMinutesPart());
String formatted = String.format("%dhrs %02dmins", hours, mins);


And just to prove the point...

import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

public class Test {

public static void main(String[] args) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH);
List<LocalDateTime> from = new ArrayList<>(5);
List<LocalDateTime> to = new ArrayList<>(5);

from.add(LocalDateTime.parse("2018-06-16 02:00:00", formatter));
from.add(LocalDateTime.parse("2018-06-16 03:00:00", formatter));
from.add(LocalDateTime.parse("2018-06-16 04:00:00", formatter));
from.add(LocalDateTime.parse("2018-06-16 05:00:00", formatter));
from.add(LocalDateTime.parse("2018-06-16 06:00:00", formatter));

to.add(LocalDateTime.parse("2018-06-18 02:00:00", formatter));
to.add(LocalDateTime.parse("2018-06-18 03:00:00", formatter));
to.add(LocalDateTime.parse("2018-06-18 04:00:00", formatter));
to.add(LocalDateTime.parse("2018-06-18 05:00:00", formatter));
to.add(LocalDateTime.parse("2018-06-18 06:00:00", formatter));

for (int index = 0; index < from.size(); index++) {
LocalDateTime fromDate = from.get(index);
LocalDateTime toDate = to.get(index);
String difference = formatDurationBetween(fromDate, toDate);
System.out.println(fromDate.format(formatter) + " - " + toDate.format(formatter) + " = " + difference);
}
}

public static String formatDurationBetween(LocalDateTime from, LocalDateTime to) {
Duration difference = Duration.between(from, to);

long days = difference.toDays();
difference = difference.minusDays(days);
long hours = difference.toHours();
long mins = difference.minusHours(hours).toMinutes();

return String.format("%dd %dh %02dm", days, hours, mins);
}

}


Outputs...

2018-06-16 02:00:00 - 2018-06-18 02:00:00 = 2d 0h 00m
2018-06-16 03:00:00 - 2018-06-18 03:00:00 = 2d 0h 00m
2018-06-16 04:00:00 - 2018-06-18 04:00:00 = 2d 0h 00m
2018-06-16 05:00:00 - 2018-06-18 05:00:00 = 2d 0h 00m
2018-06-16 06:00:00 - 2018-06-18 06:00:00 = 2d 0h 00m


You can of course make your own formatting algorithm based on your needs



Related Topics



Leave a reply



Submit