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.example.joda;

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

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("2017-01-01");
        DateMidnight end = new DateMidnight("2017-01-16");

        // 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("2017-01-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 2017-01-01 and 2017-01-16 = 15 day(s)
Days between 2017-01-01 and 2017-01-16 = 15 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

<!-- http://repo1.maven.org/maven2/joda-time/joda-time/2.9.7/joda-time-2.9.7.jar -->
<dependency>
    <groupId>joda-time</groupId>
    <artifactId>joda-time</artifactId>
    <version>2.9.7</version>
</dependency>

Wayan

Programmer, runner, recreational diver, live in the island of Bali, Indonesia. Mostly programming in Java, creating web based application with Spring Framework, Hibernate / JPA.

Leave a Reply