How do I get number of days between two dates in Joda-Time?

The following code snippet show you how to get days between two dates. You can use the `Days.daysBetween()` method and pass the dates you want to calculate. This method return a `Days` object. To get the number in days you call the `getDays()` method.

``````package org.kodejava.joda;

import org.joda.time.DateMidnight;
import org.joda.time.Days;
import org.joda.time.LocalDate;

public class DaysBetweenDemo {
public static void main(String[] args) {
// Define the start and end dates. We use the DateMidnight
// class to make sure that the calculation start from the
// midnight.
DateMidnight start = new DateMidnight("2021-07-01");
DateMidnight end = new DateMidnight("2021-07-22");

// Get days between the start date and end date.
int days = Days.daysBetween(start, end).getDays();

// Print the result.
System.out.println("Days between " +
start.toString("yyyy-MM-dd") + " and " +
end.toString("yyyy-MM-dd") + " = " +
days + " day(s)");

// Using LocalDate object.
LocalDate date1 = LocalDate.parse("2021-07-01");
LocalDate date2 = LocalDate.now();
days = Days.daysBetween(date1, date2).getDays();

// Print the result.
System.out.println("Days between " +
date1.toString("yyyy-MM-dd") + " and " +
date2.toString("yyyy-MM-dd") + " = " +
days + " day(s)");
}
}
``````

Here is the result of the program:

``````Days between 2021-07-01 and 2021-07-22 = 21 day(s)
Days between 2021-07-01 and 2021-10-29 = 120 day(s)
``````

To calculate differences between two date objects in Java 8 see the following example: How do I calculate difference between two dates?.

Maven Dependencies

``````<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>2.12.5</version>
</dependency>
``````

This site uses Akismet to reduce spam. Learn how your comment data is processed.