Number of Days between Two Dates in Java

In Java, we can use the ChronoUnit and LocalDate.until() methods to calculate the number of days between two given dates. There are other solutions also, but these solutions are the simplest and do not require importing an additional library.

1. Using ChronoUnit to Find the Number of Days between Two Dates

Using ChronoUnit.DAYS.between() API is the simplest of all solutions. This API counts the days since Epoch till both LocalDate instances and subtracts them. Internally, it is as simple as date1.toEpochDay() – date2.toEpochDay().

LocalDate start = LocalDate.parse("2023-06-01");
LocalDate end   = LocalDate.parse("2023-06-15");

long diffInDays = ChronoUnit.DAYS.between(start, end);

System.out.println(diffInDays);  //14

In the above example, we calculated the difference between two LocalDate instances in days. We can use the similar approach for other Date/time classes as well. For example, we ave used the ChronoUnit.DAYS.between() API with LocalDateTime instances.

LocalDateTime startLdt = LocalDateTime.parse("2023-06-01T02:00:00");
LocalDateTime endLdt   = LocalDateTime.parse("2023-06-15T03:00:00");

long diffInDays = ChronoUnit.DAYS.between(startLdt, endLdt);

System.out.println(diffInDays);  //14

2. Using LocalDate.until()

This solution is very much similar to using the ChronoUnit. And internally, it also uses the same technique as above i.e. date1.toEpochDay() – date2.toEpochDay().

Note that we can use the until() method with other Temporal classes such as LocalDateTime and ZonedDateTime as well.

LocalDate start = LocalDate.parse("2023-06-01");
LocalDate end   = LocalDate.parse("2023-06-15");

long diffInDays = start.until(end, ChronoUnit.DAYS);

System.out.println(diffInDays);  //14

3. Avoid using Period class

A word of caution. If we do not pass the ChronoUnit.DAYS in the above example, until() method returns a Period instance that we can use to get the difference in days.

But remember,  Period class represents the days diference in the format of “x years, y months and z days. Its getDays() method returns only the “z days” part. So if the date difference is more a 28 days, you may get incorrect results.

LocalDate start = LocalDate.parse("2023-06-01");
LocalDate end   = LocalDate.parse("2023-07-20");

long diffInDays = ChronoUnit.DAYS.between(start, end);

System.out.println(diffInDays);  //49 - Correct Result

Period period = start.until(end);

System.out.println(period.getDays());  //14  - Incorrect result

Drop me your questions related to calculating the number of days between two dates in Java.

Happy Learning !!

Sourcecode Download

Comments

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.