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

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.