How to add hours, minutes, seconds into DateTime in Joda-Time?

In this example you will learn how to add hours, minutes or seconds to a DateTime object in Joda-Time. Some methods are available to add or subtract hours, minutes or seconds from the object, as you can see in the example below.

The DateTime object is an immutable object, which means calling one of the plus() or minus() method does not modified the current object. Instead, these methods return a new DateTime object for each method calls.

In the code snippet below we call the plus() and minus() method without storing the result of the operation, we are only going to print it out. The get the new value of the DateTime object you need to assign it to a variable.

package org.kodejava.example.joda;

import org.joda.time.DateTime;

public class TimeCalculationDemo {
    public static void main(String[] args) {
        // Creates an instance of current DateTime which represents the
        // current date time.
        DateTime dateTime = new DateTime();
        System.out.println("DateTime            = " + dateTime);

        // Plus some hours, minutes, and seconds to the original DateTime.
        System.out.println("Plus 60 seconds is  = " + dateTime.plusSeconds(60));
        System.out.println("Plus 10 minutes is  = " + dateTime.plusMinutes(10));
        System.out.println("Plus 1 hour is      = " + dateTime.plusHours(1));

        // Minus some hours, minutes, and seconds to the original DateTime.
        System.out.println("Minus 60 seconds is = " + dateTime.minusSeconds(60));
        System.out.println("Minus 10 minutes is = " + dateTime.minusMinutes(10));
        System.out.println("Minus 1 hour is     = " + dateTime.minusHours(1));
    }
}

The program print the following result. The output shows the result of adding or subtracting seconds, minutes and hours the the DateTime object.

DateTime            = 2017-01-15T09:29:20.621+08:00
Plus 60 seconds is  = 2017-01-15T09:30:20.621+08:00
Plus 10 minutes is  = 2017-01-15T09:39:20.621+08:00
Plus 1 hour is      = 2017-01-15T10:29:20.621+08:00
Minus 60 seconds is = 2017-01-15T09:28:20.621+08:00
Minus 10 minutes is = 2017-01-15T09:19:20.621+08:00
Minus 1 hour is     = 2017-01-15T08:29:20.621+08:00

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 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.example.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(2017, 8, 17, 0, 0, 0);
        System.out.println("Independence Day = " + independenceDay);
    }
}

Here is the result of our program:

Milliseconds = 1250
Date Time = 2017-01-16T23:32:15.070+08:00
Independence Day = 2017-08-17T00:00:00.000+08:00

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 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.example.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 = 2017-02-16T15:37:19.746+08:00/2017-04-16T15:37:19.746+08:00
Start    = 2017-02-16T15:37:19.746+08:00
End      = 2017-04-16T15:37:19.746+08:00
Days     = 59
Hours    = 1416
Minutes  = 84960
Seconds  = 5097600
Interval = 2017-02-16T15:37:19.746+08:00/2017-05-16T15:37:19.746+08:00
Duration = PT7689600S
Days     = 89
Hours    = 2136
Minutes  = 128160
Seconds  = 7689600

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 date in Joda-Time using ISODateTimeFormat class?

This example demonstrate how to use the ISODateTimeFormat class to format the date time information in Joda-Time.

package org.kodejava.example.joda;

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

public class ISODateTimeFormatDemo {
    public static void main(String[] args) {
        DateTime dateTime = DateTime.now();

        // Returns a basic formatter for a full date as four digit
        // year, two digit month of year, and two digit day of
        // month yyyyMMdd.
        System.out.println(dateTime.toString(
                ISODateTimeFormat.basicDate()));
        System.out.println(dateTime.toString(
                ISODateTimeFormat.basicDateTime()));
        System.out.println(dateTime.toString(
                ISODateTimeFormat.basicDateTimeNoMillis()));

        // Returns a formatter for a full ordinal date, using a four
        // digit year and three digit dayOfYear yyyyDDD.
        System.out.println(dateTime.toString(
                ISODateTimeFormat.basicOrdinalDate()));

        // Returns a basic formatter for a full date as four digit
        // weekyear, two digit week of weekyear, and one digit day
        // of week xxxx'W'wwe
        System.out.println(dateTime.toString(
                ISODateTimeFormat.basicWeekDate()));
        System.out.println(dateTime.toString(
                ISODateTimeFormat.basicWeekDateTime()));
    }
}

The result of the code above is printed below:

20170116
20170116T233404.650+0800
20170116T233404+0800
2017016
2017W031
2017W031T233404.650+0800

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 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>