Java Calendar Month incrementMonthByVal(Calendar theCal, int val)

Here you can find the source of incrementMonthByVal(Calendar theCal, int val)

Description

increment Month By Val

License

Educational Community License

Declaration

private static Calendar incrementMonthByVal(Calendar theCal, int val) 

Method Source Code

//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;
    }
}

Related

  1. getMonthStr(Calendar cal)
  2. getNextMonth(Calendar calendar, int month)
  3. getNumDaysInMonth(GregorianCalendar aCalendar)
  4. getStartOfMonth(Date day, Calendar cal)
  5. incrementMonth(Calendar cal)
  6. intToCalendarMonth(int month)
  7. isFirstDayOfMonth(Calendar calendar)
  8. lastDayOfMonth(Calendar c)
  9. month(Calendar calendar)