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.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(2017, 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           = 2017-01-01
plusDays(10)   = 2017-01-11
plusWeeks(9)   = 2017-03-05
plusMonths(2)  = 2017-03-01
plusYears(1)   = 2018-01-01
minusDays(10)  = 2016-12-22
minusWeeks(9)  = 2016-10-30
minusMonths(2) = 2016-11-01
minusYears(1)  = 2016-01-01
Wayan Saryada

Wayan Saryada

A programmer, runner, recreational diver, currently living in the island of Bali, Indonesia. Mostly programming in Java, creating web based application with Spring Framework, Hibernate / JPA.
Wayan Saryada

Leave a Reply