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

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;

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("2010-02-01");
        DateMidnight end = new DateMidnight("2012-02-07");

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

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

Here is the result of the program:

Days between 2010-02-01 and 2012-02-07 = 736 day(s)

How do I get date / time fields of date in Joda?

In Joda the date and time information are divided into fields. The following example show you some fields that can be obtained from the DateTime object. For example to get the day of the year we use the getDayOfYear() method and to get the day of week we can use the getDayOfWeek() method.

package org.kodejava.example.joda;

import org.joda.time.DateTime;

public class DateTimeFieldDemo {
    public static void main(String[] args) {
        DateTime dateTime = new DateTime();
        System.out.println("dateTime = " + dateTime);

        // Get day of year, day of month, day of week and week of
        // year of a date.
        System.out.println("DOY = " + dateTime.getDayOfYear());
        System.out.println("DOM = " + dateTime.getDayOfMonth());
        System.out.println("DOW = " + dateTime.getDayOfWeek());
        System.out.println("WOW = " + dateTime.getWeekOfWeekyear());

        // Get hour of day, minute of hour and second of minute.
        System.out.println("HOD = " + dateTime.getHourOfDay());
        System.out.println("MOH = " + dateTime.getMinuteOfHour());
        System.out.println("SOM = " + dateTime.getSecondOfMinute());

        // Get minute of day and second of day.
        System.out.println("MOD = " + dateTime.getMinuteOfDay());
        System.out.println("SOD = " + dateTime.getSecondOfDay());
    }
}

The outputs of our program are:

dateTime = 2016-02-06T20:05:07.944+08:00
DOY = 37
DOM = 6
DOW = 6
WOW = 5
HOD = 20
MOH = 5
SOM = 7
MOD = 1205
SOD = 72307