Add a number of months to a date returning a new object in Java

Description

The following code shows how to add a number of months to a date returning a new object.

Example


//from w w w  .  jav a  2 s .  c om
import java.util.Calendar;
import java.util.Date;

public class Main {
  public static Date addMonths(Date date, int amount) {
    return add(date, Calendar.MONTH, amount);
  }

  private static Date add(Date date, int calendarField, int amount) {
    if (date == null) {
      throw new IllegalArgumentException("The date must not be null");
    }
    Calendar c = Calendar.getInstance();
    c.setTime(date);
    c.add(calendarField, amount);
    return c.getTime();
  }

  public static void main(String[] argv) {
    Date date = new Date();

    System.out.println(addMonths(date, 100));
  }
}

The code above generates the following result.





















Home »
  Java Tutorial »
    Date »




Date Get
Date Set
Date Format
Date Compare
Date Convert
Date Calculation
Date Parse
Timezone