How do I use Joda-Time’s Instant Class?

An instant in the datetime continuum specified as a number of milliseconds from 1970-01-01T00:00Z. Some classes that represent an instance in the Joda-Time library includes the Instant, DateTime, DateMidnight and MutableDateTime classes.

package org.kodejava.joda;

import org.joda.time.DateTime;
import org.joda.time.Instant;

public class InstantDemo {
    public static void main(String[] args) {
        // An instant in the datetime continuum specified as
        // a number of milliseconds from 1970-01-01T00:00Z.
        //
        // The declaration below creates 1 seconds instant from
        // 1970.
        Instant instant = new Instant(1000);

        // Get a new copy of instant with 500 duration added.
        instant = instant.plus(500);

        // Get a new copy of instant with 250 duration taken away.
        instant = instant.minus(250);
        System.out.println("Milliseconds = " + instant.getMillis());

        // Creating an instant that represent the current date.
        DateTime dateTime = new DateTime();
        System.out.println("Date Time = " + dateTime);

        // Creating an instant of a specific date and time.
        DateTime independenceDay = new DateTime(1945, 8, 17, 0, 0, 0);
        System.out.println("Independence Day = " + independenceDay);
    }
}

Here is the result of our program:

Date Time = 2021-10-29T08:58:30.011+08:00
Independence Day = 1945-08-17T00:00:00.000+09:00

Maven Dependencies

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

Maven Central

How do I use the Interval class of Joda-Time?

This example show you how to use the org.joda.time.Interval class in Joda-Time. A time interval represents a period of time between two instants. Intervals are inclusive of the start instant and exclusive of the end. The end instant is always greater than or equal to the start instant.

package org.kodejava.joda;

import org.joda.time.DateTime;
import org.joda.time.Duration;
import org.joda.time.Interval;
import org.joda.time.Months;

public class IntervalDemo {
    public static void main(String[] args) {
        DateTime startDate = new DateTime();
        DateTime endDate = startDate.plus(Months.months(2));

        // Creates an interval from a start to an end instant.
        Interval interval = new Interval(startDate, endDate);
        System.out.println("Interval = " + interval);
        System.out.println("Start    = " + interval.getStart());
        System.out.println("End      = " + interval.getEnd());

        System.out.println("Days     = " + interval.toDuration().getStandardDays());
        System.out.println("Hours    = " + interval.toDuration().getStandardHours());
        System.out.println("Minutes  = " + interval.toDuration().getStandardMinutes());
        System.out.println("Seconds  = " + interval.toDuration().getStandardSeconds());

        // Add one more month to the interval
        interval = interval.withEnd(interval.getEnd().plusMonths(1));
        System.out.println("Interval = " + interval);

        // Gets the duration of this time interval
        Duration duration = interval.toDuration();
        System.out.println("Duration = " + duration);
        System.out.println("Days     = " + duration.getStandardDays());
        System.out.println("Hours    = " + duration.getStandardHours());
        System.out.println("Minutes  = " + duration.getStandardMinutes());
        System.out.println("Seconds  = " + duration.getStandardSeconds());
    }
}

Below is the result printed by our program:

Interval = 2021-10-29T07:30:29.811+08:00/2021-12-29T07:30:29.811+08:00
Start    = 2021-10-29T07:30:29.811+08:00
End      = 2021-12-29T07:30:29.811+08:00
Days     = 61
Hours    = 1464
Minutes  = 87840
Seconds  = 5270400
Interval = 2021-10-29T07:30:29.811+08:00/2022-01-29T07:30:29.811+08:00
Duration = PT7948800S
Days     = 92
Hours    = 2208
Minutes  = 132480
Seconds  = 7948800

Maven Dependencies

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

Maven Central

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.7</version>
</dependency>

Maven Central

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 get the last day of a month in Joda-Time?

This example show us how to use Joda-Time’s DateTime class to get the last day of the month. To get the last day of the month we first need to find out the last date of the month. To do this, create a new instance of a DateTime. From the DateTime object get the day-of-the-month property by calling the dayOfMonth() method. Then call the withMaximumValue() method which will give us the last date of a month.

To get the day name, we call the DateTime‘s dayOfWeek() method followed by a call to the getAsText() method to get the name of the day. Let’s see the code snippet below:

package org.kodejava.joda;

import org.joda.time.DateTime;
import org.joda.time.LocalDate;

public class LastDayOfTheMonth {
    public static void main(String[] args) {
        // Creates an instance of DateTime.
        DateTime dateTime = DateTime.now();

        // Get the last date of the month using the dayOfMonth property
        // and get the maximum value from it.
        DateTime lastDate = dateTime.dayOfMonth().withMaximumValue();

        // Print the date and day name.
        System.out.println("Last date of the month = " + lastDate);
        System.out.println("Last day of the month  = " +
                lastDate.dayOfWeek().getAsText());

        // If you know the last date of the month you can simply parse the
        // date string and get the name of the last day of the month.
        String day = LocalDate.parse("2021-10-31").dayOfWeek().getAsText();
        System.out.println("Day  = " + day);
    }
}

If you know the last date of the month you can simply parse the date string to create a DateTime object or a LocalDate object and call the dayOfWeek() method and get the name of the day using getAsText() method.

The example output is:

Last date of the month = 2021-10-31T06:37:18.069+08:00
Last day of the month  = Sunday
Day  = Sunday

Maven Dependencies

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

Maven Central