Get Number of Days between Two Dates

Learn to calculate the number of days between two dates in Java using ChronoUnit.DAYS.between() and LocalDate.until() methods.

1. ChronoUnit.DAYS.between()

This is the simplest of all solutions. Internally, it is as simple as date1.toEpochDay() - date2.toEpochDay(). It counts the days since Epoch till both LocalDate instances and subtracts them.

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

public class DaysBetweenDates
{
	public static void main(String[] args)
	{
		LocalDate date1 = LocalDate.now();
		LocalDate date2 = date1.plusDays(99);

		long diffInDays = ChronoUnit.DAYS.between(date1, date2);

		System.out.println(diffInDays);  // 99
	}
}

2. LocalDate.until()

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

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

public class DaysBetweenDates
{
	public static void main(String[] args)
	{
		LocalDate date1 = LocalDate.now();
		LocalDate date2 = date1.plusDays(99);

		long diffInDays = date1.until(date2, ChronoUnit.DAYS);

		System.out.println(diffInDays);  // 99
	}
}

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

Happy Learning !!

Sourcecode Download

Was this post helpful?

Join 7000+ Awesome Developers

Get the latest updates from industry, awesome resources, blog updates and much more.

* We do not spam !!

Leave a Comment

HowToDoInJava

A blog about Java and related technologies, the best practices, algorithms, and interview questions.