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.example.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("2016-06-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("2016-03-25");
        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 2016-06-01 and 2017-01-16 = 7 month(s)
Months between 2016-03-25 and 2017-01-16 = 9 month(s)

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>

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.example.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("dateTime = " + dateTime);
        System.out.println("date     = " + date);

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

The result of our code snippet:

dateTime = 2017-01-16T14:06:22.332+08:00
date     = Mon Jan 16 14:06:22 WITA 2017
calendar = java.util.GregorianCalendar[time=1484546782332,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="Asia/Makassar",offset=28800000,dstSavings=0,useDaylight=false,transitions=5,lastRule=null],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2017,MONTH=0,WEEK_OF_YEAR=3,WEEK_OF_MONTH=3,DAY_OF_MONTH=16,DAY_OF_YEAR=16,DAY_OF_WEEK=2,DAY_OF_WEEK_IN_MONTH=3,AM_PM=1,HOUR=2,HOUR_OF_DAY=14,MINUTE=6,SECOND=22,MILLISECOND=332,ZONE_OFFSET=28800000,DST_OFFSET=0]

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>

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.example.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(2017, 1, 1);
        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           = 2017-01-01
plusDays(10)   = 2017-01-11
plusWeeks(9)   = 2017-03-05
plusMonths(2)  = 2017-03-01
plusYears(1)   = 2018-01-01
minusDays(10)  = 2016-12-22
minusWeeks(9)  = 2016-10-30
minusMonths(2) = 2016-11-01
minusYears(1)  = 2016-01-01

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>

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.example.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 an the example result of our program:

Pattern  = E MM/dd/yyyy HH:mm:ss.SSS
Default  = Mon 01/16/2017 10:53:32.939
Germany  = Mo 01/16/2017 10:53:32.939
French   = lun. 01/16/2017 10:53:32.939
Japanese = 月 01/16/2017 10:53:32.939
fullDate   = Monday, January 16, 2017
longDate   = January 16, 2017
mediumDate = Jan 16, 2017
shortDate  = 1/16/17
dd/MM/yyyy = 16/01/2017

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>

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.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 = 2017-01-16T09:43:36.662+08:00
DOY = 16
DOM = 16
DOW = 1
WOW = 3
HOD = 9
MOH = 43
SOM = 36
MOD = 583
SOD = 35016

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>