Here you can find the source of incrementMonthByVal(Calendar theCal, int val)
private static Calendar incrementMonthByVal(Calendar theCal, int val)
//package com.java2s; //License from project: Educational Community License import java.util.Calendar; public class Main { private static Calendar incrementMonthByVal(Calendar theCal, int val) { // this increments by the val // for dates of the form MM/[1-28]/YYYY this simply results in MM+1/[1-28]/YYYY // for dates of the form MM/[29-31]/YYYY this will increment the month, set the day // to the closest available value to the original without overflowing into the next month Calendar incrementedCalendar = (Calendar) theCal.clone(); int currentDay = incrementedCalendar.get(Calendar.DAY_OF_MONTH); incrementedCalendar.add(Calendar.MONTH, val); incrementedCalendar.set(Calendar.DAY_OF_MONTH, currentDay); int newDay = incrementedCalendar.get(Calendar.DAY_OF_MONTH); if (newDay < currentDay) { //we overflowed the "DAY_OF_MONTH" field, i.e. tried to set the date to February 31st. incrementedCalendar.roll(Calendar.DAY_OF_MONTH, false); int rolledBackDay = incrementedCalendar .get(Calendar.DAY_OF_MONTH); while (rolledBackDay < newDay) { incrementedCalendar.roll(Calendar.DAY_OF_MONTH, false); rolledBackDay = incrementedCalendar .get(Calendar.DAY_OF_MONTH); }// w ww .j a v a 2 s. co m incrementedCalendar.roll(Calendar.MONTH, false); } return incrementedCalendar; } }