Calculating the Difference Between Two Java Date Instances

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()

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

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

java.util.Date Calculate difference in days

Oh yes a better solution there is!

Stop using the outmoded java.util.Date class and embrace the power of the java.time API built into Java 8 and later (tutorial). Specifically, the DateTimeFormatter, LocalDate, and ChronoUnit classes.

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM-dd-yyyy");
LocalDate date1 = LocalDate.parse("03-29-2015", formatter);
LocalDate date2 = LocalDate.parse("03-30-2015", formatter);
long days = ChronoUnit.DAYS.between(date1, date2);
System.out.println(days); // prints 1

How to calculate the difference between two dates in hours with java?

Try This :

    System.out.print("Enter Time-in(hh:mm)");
String start=input.next(); //make sure it have "hh:mm" format
LocalTime userTime = LocalTime.parse(start);
LocalTime currentTime = LocalTime.now();


long diff = ChronoUnit.HOURS.between(currentTime, userTime);

Java 8: Difference between two LocalDateTime in multiple units

Unfortunately, there doesn't seem to be a period class that spans time as well, so you might have to do the calculations on your own.

Fortunately, the date and time classes have a lot of utility methods that simplify that to some degree. Here's a way to calculate the difference although not necessarily the fastest:

LocalDateTime fromDateTime = LocalDateTime.of(1984, 12, 16, 7, 45, 55);
LocalDateTime toDateTime = LocalDateTime.of(2014, 9, 10, 6, 40, 45);

LocalDateTime tempDateTime = LocalDateTime.from( fromDateTime );

long years = tempDateTime.until( toDateTime, ChronoUnit.YEARS );
tempDateTime = tempDateTime.plusYears( years );

long months = tempDateTime.until( toDateTime, ChronoUnit.MONTHS );
tempDateTime = tempDateTime.plusMonths( months );

long days = tempDateTime.until( toDateTime, ChronoUnit.DAYS );
tempDateTime = tempDateTime.plusDays( days );


long hours = tempDateTime.until( toDateTime, ChronoUnit.HOURS );
tempDateTime = tempDateTime.plusHours( hours );

long minutes = tempDateTime.until( toDateTime, ChronoUnit.MINUTES );
tempDateTime = tempDateTime.plusMinutes( minutes );

long seconds = tempDateTime.until( toDateTime, ChronoUnit.SECONDS );

System.out.println( years + " years " +
months + " months " +
days + " days " +
hours + " hours " +
minutes + " minutes " +
seconds + " seconds.");

//prints: 29 years 8 months 24 days 22 hours 54 minutes 50 seconds.

The basic idea is this: create a temporary start date and get the full years to the end. Then adjust that date by the number of years so that the start date is less then a year from the end. Repeat that for each time unit in descending order.

Finally a disclaimer: I didn't take different timezones into account (both dates should be in the same timezone) and I also didn't test/check how daylight saving time or other changes in a calendar (like the timezone changes in Samoa) affect this calculation. So use with care.

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()

Calculate days between two Dates in Java 8

If you want logical calendar days, use DAYS.between() method from java.time.temporal.ChronoUnit:

LocalDate dateBefore;
LocalDate dateAfter;
long daysBetween = DAYS.between(dateBefore, dateAfter);

If you want literal 24 hour days, (a duration), you can use the Duration class instead:

LocalDate today = LocalDate.now()
LocalDate yesterday = today.minusDays(1);
// Duration oneDay = Duration.between(today, yesterday); // throws an exception
Duration.between(today.atStartOfDay(), yesterday.atStartOfDay()).toDays() // another option

For more information, refer to this document.



Related Topics



Leave a reply



Submit