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 modify 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.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            = 2021-10-31T22:56:55.715+08:00
Plus 60 seconds is  = 2021-10-31T22:57:55.715+08:00
Plus 10 minutes is  = 2021-10-31T23:06:55.715+08:00
Plus 1 hour is      = 2021-10-31T23:56:55.715+08:00
Minus 60 seconds is = 2021-10-31T22:55:55.715+08:00
Minus 10 minutes is = 2021-10-31T22:46:55.715+08:00
Minus 1 hour is     = 2021-10-31T21:56:55.715+08:00

Maven Dependencies

<!--https://search.maven.org/remotecontent?filepath=joda-time/joda-time/2.10.13/joda-time-2.10.13.jar-->
<dependency>
    <groupId>joda-time</groupId>
    <artifactId>joda-time</artifactId>
    <version>2.10.13</version>
</dependency>

Maven Central

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

20211029
20211029T091631.884+0800
20211029T091631+0800
2021302
2021W435
2021W435T091631.884+0800

Maven Dependencies

<!--https://search.maven.org/remotecontent?filepath=joda-time/joda-time/2.10.13/joda-time-2.10.13.jar-->
<dependency>
    <groupId>joda-time</groupId>
    <artifactId>joda-time</artifactId>
    <version>2.10.13</version>
</dependency>

Maven Central

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

<!--https://search.maven.org/remotecontent?filepath=joda-time/joda-time/2.10.13/joda-time-2.10.13.jar-->
<dependency>
    <groupId>joda-time</groupId>
    <artifactId>joda-time</artifactId>
    <version>2.10.13</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

<!--https://search.maven.org/remotecontent?filepath=joda-time/joda-time/2.10.13/joda-time-2.10.13.jar-->
<dependency>
    <groupId>joda-time</groupId>
    <artifactId>joda-time</artifactId>
    <version>2.10.13</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

<!--https://search.maven.org/remotecontent?filepath=joda-time/joda-time/2.10.13/joda-time-2.10.13.jar-->
<dependency>
    <groupId>joda-time</groupId>
    <artifactId>joda-time</artifactId>
    <version>2.10.13</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

<!--https://search.maven.org/remotecontent?filepath=joda-time/joda-time/2.10.13/joda-time-2.10.13.jar-->
<dependency>
    <groupId>joda-time</groupId>
    <artifactId>joda-time</artifactId>
    <version>2.10.13</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

<!--https://search.maven.org/remotecontent?filepath=joda-time/joda-time/2.10.13/joda-time-2.10.13.jar-->
<dependency>
    <groupId>joda-time</groupId>
    <artifactId>joda-time</artifactId>
    <version>2.10.13</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

<!--https://search.maven.org/remotecontent?filepath=joda-time/joda-time/2.10.13/joda-time-2.10.13.jar-->
<dependency>
    <groupId>joda-time</groupId>
    <artifactId>joda-time</artifactId>
    <version>2.10.13</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

<!--https://search.maven.org/remotecontent?filepath=joda-time/joda-time/2.10.13/joda-time-2.10.13.jar-->
<dependency>
    <groupId>joda-time</groupId>
    <artifactId>joda-time</artifactId>
    <version>2.10.13</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

<!--https://search.maven.org/remotecontent?filepath=joda-time/joda-time/2.10.13/joda-time-2.10.13.jar-->
<dependency>
    <groupId>joda-time</groupId>
    <artifactId>joda-time</artifactId>
    <version>2.10.13</version>
</dependency>

Maven Central