Calculate days between two Dates in Java 8

315,386

Solution 1

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.

Solution 2

Based on VGR's comments here is what you can use:

ChronoUnit.DAYS.between(firstDate, secondDate)

Solution 3

You can use until:

LocalDate independenceDay = LocalDate.of(2014, Month.JULY, 4);
LocalDate christmas = LocalDate.of(2014, Month.DECEMBER, 25);

System.out.println("Until christmas: " + independenceDay.until(christmas));
System.out.println("Until christmas (with crono): " + independenceDay.until(christmas, ChronoUnit.DAYS));

Output:

Until christmas: P5M21D
Until christmas (with crono): 174

As mentioned in a comment, if no unit is specified until returns Period.

Snippet from the documentation:

A date-based amount of time in the ISO-8601 calendar system, such as '2 years, 3 months and 4 days'.
This class models a quantity or amount of time in terms of years, months, and days. See Duration for the time-based equivalent to this class.

Solution 4

DAYS.between

You can use DAYS.between from java.time.temporal.ChronoUnit

e.g.

import java.time.temporal.ChronoUnit;
...

long totalDaysBetween(LocalDate dateBefore, LocalDate dateAfter) {
    return DAYS.between(dateBefore, dateAfter);

Solution 5

If startDate and endDate are instance of java.util.Date

We can use the between( ) method from ChronoUnit enum:

public long between(Temporal temporal1Inclusive, Temporal temporal2Exclusive) {
    //..
}

ChronoUnit.DAYS count days which completed 24 hours.

import java.time.temporal.ChronoUnit;

ChronoUnit.DAYS.between(startDate.toInstant(), endDate.toInstant());

//OR 

ChronoUnit.DAYS.between(Instant.ofEpochMilli(startDate.getTime()), Instant.ofEpochMilli(endDate.getTime()));
Share:
315,386
Marcos
Author by

Marcos

Updated on November 29, 2021

Comments

  • Marcos
    Marcos over 2 years

    I know there are lots of questions on SO about how to get Dates in Java, but I want an example using new Java 8 Date API. I also know about the JodaTime library, but I want a method without relying on external libraries.

    The function needs to be compliant with these restrictions:

    1. Prevent errors from date savetime
    2. Inputs are two Date objects (without time, I know about LocalDateTime, but I need to do this with Date instances)
  • VGR
    VGR over 9 years
    That throws an exception, because the Duration.between method requires temporal objects capable of supporting the SECONDS unit. Instead, try Duration.between(today.atTime(0, 0), yesterday.atTime(0, 0)).toDays().
  • eee
    eee over 9 years
    Instead of today.atTime(0, 0) you can do today.atStartOfDay().
  • assylias
    assylias over 9 years
    @REACHUS Maybe the -1 was a bit harsh because the code you propose works, but Duration is meant to measure "time-based amounts of time". There is a built-in way to measure a number of days which does not require converting from date to datetime.
  • nafg
    nafg over 6 years
    FWIW... I'm not sure why both exist. Are there times that one is more readable and times that the other is? When/why?
  • M. Justin
    M. Justin almost 6 years
    The gotcha I just encountered with the first version of until is that it returns a Period object. That'll return a number of years/months/days between the two dates, not the actual number of days. And getDays() on the Period only returns the days part (not taking into account the number of years or months), rather than the total number of days. The second version works exactly as desired to get a number of days between two dates.
  • ralphgabb
    ralphgabb about 5 years
    Is there's a complete alternative for this for this ? Since it needs Android SDk 26 and above
  • MrSmith42
    MrSmith42 about 5 years
    In fall in the trap to use ' Period.between(date1, date2).getDays()' without realizing that you loose the months and years of the difference.
  • Paul
    Paul about 4 years
    The better answer for LocalDate's is @Sunil B's answer below: ChronoUnit.DAYS.between(firstDate, secondDate)
  • syntagma
    syntagma about 4 years
    @Lappro why is it better? It uses the same method as my answer
  • Paul
    Paul about 4 years
    @syntagma Ah right your first example is indeed the same, I didn't see that because the DAYS came from an import instead of ChronoUnit.DAYS. And glancing over details to find a quick solution isn't always the best strategy on my part ;)
  • Malleswar Reddy
    Malleswar Reddy almost 4 years
    java.time.temporal.ChronoUnit java 8 implemancation
  • Dima Kozhevin
    Dima Kozhevin almost 4 years
    Please don't post only code as answer, but also provide an explanation what your code does and how it solves the problem of the question. Answers with an explanation are usually more helpful and of better quality, and are more likely to attract upvotes.
  • S. Pauk
    S. Pauk over 3 years
    This solution should be the accepted answer since it is more concise.