Calculate days between two Dates in Java 8
I know there are lots of questions on SO about how to get Date
s 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:
- Prevent errors from date savetime
- Inputs are two
Date
objects (without time, I know aboutLocalDateTime
, but I need to do this withDate
instances)
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.
Based on VGR's comments here is what you can use:
ChronoUnit.DAYS.between(firstDate, secondDate)
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 at comment - first untill()
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.