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
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, JPA, etc. If you need help on Java programming you can hire me on Fiverr.
Wayan Saryada

Leave a Reply