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

In this example you’ll learn how to add some hours, minutes or seconds into the DateTime object in Joda Time. Some couple methods available to plus or minus some 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 method return a new DateTime object for each method calls.

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 1 hour is " + dateTime.plusHours(1));
        System.out.println("Plus 10 minutes is " + dateTime.plusMinutes(10));
        System.out.println("Plus 60 seconds is " + dateTime.plusSeconds(60));

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

The program print the following result:

DateTime = 2012-07-27T12:08:46.048+08:00
Plus 1 hour is 2012-07-27T13:08:46.048+08:00
Plus 10 minutes is 2012-07-27T12:18:46.048+08:00
Plus 60 seconds is 2012-07-27T12:09:46.048+08:00
Minus 1 hour is 2012-07-27T11:08:46.048+08:00
Minus 10 minutes is 2012-07-27T11:58:46.048+08:00
Minus 60 seconds is 2012-07-27T12:07:46.048+08:00

How do I format date in Joda using ISODateTimeFormat class?

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

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 = new DateTime();

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

20120228
20120228T163810.037+0800
20120228T163810+0800
2012059
2012W092
2012W092T163810.037+0800

How do I use Joda Time 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(2012, 8, 17, 0, 0, 0);
        System.out.println("Independence Day = " + independenceDay);
    }
}

Here is the result of our program:

Milliseconds = 1250
Date Time = 2012-02-28T17:03:45.257+08:00

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. An interval object represent an interval of time from one millisecond instant to another 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());

        //
        // 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);
    }
}

Below is the result printed by our program:

Interval = 2012-02-28T17:53:36.997/2012-04-28T17:53:36.997
Start    = 2012-02-28T17:53:36.997+08:00
End      = 2012-04-28T17:53:36.997+08:00
Interval = 2012-02-28T17:53:36.997/2012-05-28T17:53:36.997
Duration = PT7776000S

How do I get number of days between two dates in Joda?

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;

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("2010-02-01");
        DateMidnight end = new DateMidnight("2012-02-07");

        // Get days between the start date and end date.
        int days = Days.daysBetween(start, end).getDays();

        System.out.println("Days between " +
                start.toString("yyyy-MM-dd") + " and " +
                end.toString("yyyy-MM-dd") + " = " +
                days + " day(s)");
    }
}

Here is the result of the program:

Days between 2010-02-01 and 2012-02-07 = 736 day(s)

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

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.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("2010-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)");
    }
}

Here is the output of our program:

Months between 2010-01-01 and 2012-02-07 = 25 month(s)

How do I convert 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.

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 = new DateTime();
        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);
    }
}

How do I do a date calculations?

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(2012, 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           = 2012-01-01
plusDays(10)   = 2012-01-11
plusWeeks(9)   = 2012-03-04
plusMonths(2)  = 2012-03-01
plusYears(1)   = 2013-01-01
minusDays(10)  = 2011-12-22
minusWeeks(9)  = 2011-10-30
minusMonths(2) = 2011-11-01
minusYears(1)  = 2011-01-01

How do I format date information in Joda?

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 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 dateTime = new DateTime();

        //
        // Print out the date as a formatted string using the defined
        // Locale information.
        //
        System.out.println(dateTime.toString(pattern));
        System.out.println(dateTime.toString(pattern, Locale.GERMANY));
        System.out.println(dateTime.toString(pattern, Locale.FRENCH));
        System.out.println(dateTime.toString(pattern, Locale.JAPANESE));
    }
}

Here an the example result of our program:

Fri 02/03/2012 17:21:14.480
Fr 02/03/2012 17:21:14.480
ven. 02/03/2012 17:21:14.480
金 02/03/2012 17:21:14.480

How do I get date / time fields of date in Joda?

In Joda 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 = 2016-02-06T20:05:07.944+08:00
DOY = 37
DOM = 6
DOW = 6
WOW = 5
HOD = 20
MOH = 5
SOM = 7
MOD = 1205
SOD = 72307