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

The code below show you how to use the Months class to calculate the different in months between two dates.

package org.kodejava.joda;

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

import java.util.Date;

public class MonthsBetweenDemo {
    public static void main(String[] args) {
        // Creates an instance of start and end dates.
        DateMidnight start = new DateMidnight("2021-01-01");
        DateMidnight end = new DateMidnight(new Date());

        // Get months between these dates.
        int months = Months.monthsBetween(start, end).getMonths();

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

        // Using LocalDate object.
        LocalDate date1 = LocalDate.parse("2021-03-01");
        LocalDate date2 = LocalDate.now();
        months = Months.monthsBetween(date1, date2).getMonths();

        // Print the result.
        System.out.println("Months between " +
                date1.toString("yyyy-MM-dd") + " and " +
                date2.toString("yyyy-MM-dd") + " = " +
                months + " month(s)");
    }
}

Here is the output of our program:

Months between 2021-01-01 and 2021-10-29 = 9 month(s)
Months between 2021-03-01 and 2021-10-29 = 7 month(s)

Maven Dependencies

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

Maven Central

How do I convert Joda-Time’s DateTime into Calendar or Date object?

This code snippet show you how to convert Joda-Time’s DateTime object into JDK’s java.util.Calendar or java.util.Date object. To convert DateTime to java.util.Date we use the toDate() method and to convert to java.util.Calendar we use the toCalendar() method.

package org.kodejava.joda;

import org.joda.time.DateTime;

import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

public class DateTimeToDateCalendarDemo {
    public static void main(String[] args) {
        // Converting DateTime object into JDK's Date.
        DateTime dateTime = DateTime.now();
        Date date = dateTime.toDate();
        System.out.println("org.joda.time.DateTime = " + dateTime);
        System.out.println("java.util.Date         = " + date);

        // Converting DateTime object into JDK's Calendar.
        Calendar calendar = dateTime.toCalendar(Locale.getDefault());
        System.out.println("java.util.Calendar     = " + calendar);
    }
}

The result of our code snippet:

org.joda.time.DateTime = 2021-10-29T06:54:29.003+08:00
java.util.Date         = Fri Oct 29 06:54:29 CST 2021
java.util.Calendar     = java.util.GregorianCalendar[time=1635461669003,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="Asia/Shanghai",offset=28800000,dstSavings=0,useDaylight=false,transitions=31,lastRule=null],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2021,MONTH=9,WEEK_OF_YEAR=44,WEEK_OF_MONTH=5,DAY_OF_MONTH=29,DAY_OF_YEAR=302,DAY_OF_WEEK=6,DAY_OF_WEEK_IN_MONTH=5,AM_PM=0,HOUR=6,HOUR_OF_DAY=6,MINUTE=54,SECOND=29,MILLISECOND=3,ZONE_OFFSET=28800000,DST_OFFSET=0]

Maven Dependencies

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

Maven Central

How do I do a date calculations in Joda-Time?

Using the Joda-Time library can simplify the date calculation process. For instance, we can add or subtract some days, weeks, months or year easily. There are a plus and minus method for this operation. For instance if you want to add 9 weeks to date object you can do something like date.plusWeeks(9).

package org.kodejava.joda;

import org.joda.time.LocalDate;

public class DateCalculationDemo {
    public static void main(String[] args) {
        // Creates an instance of LocalDate where we are going to do
        // some date calculations.
        LocalDate date = new LocalDate(2021, 10, 29);
        System.out.println("Date           = " + date);

        // Add days, weeks, months, year value into the date object.
        System.out.println("plusDays(10)   = " + date.plusDays(10));
        System.out.println("plusWeeks(9)   = " + date.plusWeeks(9));
        System.out.println("plusMonths(2)  = " + date.plusMonths(2));
        System.out.println("plusYears(1)   = " + date.plusYears(1));

        // Subtract days, weeks, months, year value from date object.
        System.out.println("minusDays(10)  = " + date.minusDays(10));
        System.out.println("minusWeeks(9)  = " + date.minusWeeks(9));
        System.out.println("minusMonths(2) = " + date.minusMonths(2));
        System.out.println("minusYears(1)  = " + date.minusYears(1));
    }
}

The output of the program above are:

Date           = 2021-10-29
plusDays(10)   = 2021-11-08
plusWeeks(9)   = 2021-12-31
plusMonths(2)  = 2021-12-29
plusYears(1)   = 2022-10-29
minusDays(10)  = 2021-10-19
minusWeeks(9)  = 2021-08-27
minusMonths(2) = 2021-08-29
minusYears(1)  = 2020-10-29

Maven Dependencies

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

Maven Central

How do I format DateTime object in Joda-Time?

The example show you how to format the string representation of a date. In Joda we can use the DateTime‘s class toString() method. The method accept the pattern of the date format and the locale information.

package org.kodejava.joda;

import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;

import java.util.Locale;

public class FormattingDemo {
    // Define the date format pattern.
    private static final String pattern = "E MM/dd/yyyy HH:mm:ss.SSS";

    public static void main(String[] args) {
        // Creates a new instance of DateTime object.
        DateTime dt = DateTime.now();

        // Print out the date as a formatted string using the defined
        // Locale information.
        System.out.println("Pattern  = " + pattern);
        System.out.println("Default  = " + dt.toString(pattern));
        System.out.println("Germany  = " + dt.toString(pattern, Locale.GERMANY));
        System.out.println("French   = " + dt.toString(pattern, Locale.FRENCH));
        System.out.println("Japanese = " + dt.toString(pattern, Locale.JAPANESE));

        // Using predefined format from DateTimeFormat class.
        System.out.println("fullDate   = " + dt.toString(DateTimeFormat.fullDate()));
        System.out.println("longDate   = " + dt.toString(DateTimeFormat.longDate()));
        System.out.println("mediumDate = " + dt.toString(DateTimeFormat.mediumDate()));
        System.out.println("shortDate  = " + dt.toString(DateTimeFormat.shortDate()));
        System.out.println("dd/MM/yyyy = " + dt.toString(DateTimeFormat.forPattern("dd/MM/yyyy")));
    }
}

Here are the example result of our program:

Pattern  = E MM/dd/yyyy HH:mm:ss.SSS
Default  = Fri 10/29/2021 06:49:32.491
Germany  = Fr. 10/29/2021 06:49:32.491
French   = ven. 10/29/2021 06:49:32.491
Japanese = 金 10/29/2021 06:49:32.491
fullDate   = Friday, October 29, 2021
longDate   = October 29, 2021
mediumDate = Oct 29, 2021
shortDate  = 10/29/21
dd/MM/yyyy = 29/10/2021

Maven Dependencies

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

Maven Central

How do I get date and time fields of DateTime object in Joda-Time?

In Joda-Time 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.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("Day of Year       = " + dateTime.getDayOfYear());
        System.out.println("Day of Month      = " + dateTime.getDayOfMonth());
        System.out.println("Day of Week       = " + dateTime.getDayOfWeek());
        System.out.println("Week of Week year = " + dateTime.getWeekOfWeekyear());

        // Get hour of day, minute of hour and second of minute.
        System.out.println("Hour of Day       = " + dateTime.getHourOfDay());
        System.out.println("Minute of Hour    = " + dateTime.getMinuteOfHour());
        System.out.println("Second of Minute  = " + dateTime.getSecondOfMinute());

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

The outputs of our program are:

DateTime          = 2021-10-29T06:46:49.259+08:00
Day of Year       = 302
Day of Month      = 29
Day of Week       = 5
Week of Week year = 43
Hour of Day       = 6
Minute of Hour    = 46
Second of Minute  = 49
Minute of Day     = 406
Second of Day     = 24409

Maven Dependencies

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

Maven Central