Java Month Next nextMonth(Date then)

Here you can find the source of nextMonth(Date then)

Description

next Month

License

Apache License

Declaration

public static Date nextMonth(Date then) 

Method Source Code

//package com.java2s;
//License from project: Apache License 

import java.util.Calendar;
import java.util.Date;

public class Main {
    private static final int[] incrementSequence = new int[] { Calendar.SECOND, Calendar.MINUTE,
            Calendar.HOUR_OF_DAY, Calendar.DAY_OF_MONTH, Calendar.MONTH, Calendar.YEAR, Calendar.ERA };

    public static Date nextMonth(Date then) {
        return next(then, Calendar.MONTH, 1, 0);
    }/*from   w w w. j a va  2  s .c  o m*/

    public static Date nextMonth() {
        return nextMonth(new Date());
    }

    public static Date next(Date then, int calendarField, int multiple, int minimalDelta) {
        int calendarFieldIncrementIndex = getIncrementSequenceIndex(calendarField);
        int nextSmallestCalendarField = calendarFieldIncrementIndex > 0
                ? incrementSequence[calendarFieldIncrementIndex - 1]
                : Calendar.MILLISECOND;

        Calendar calThen = Calendar.getInstance();
        calThen.setTime(then);

        calThen.add(nextSmallestCalendarField, minimalDelta); // always at least a second late if its a minute, a minute of its an hour, etc ...

        Calendar calResult = (Calendar) calThen.clone();
        calResult.add(calendarField, multiple);
        for (int index = calendarFieldIncrementIndex - 1; index >= 0; --index)
            calResult.set(incrementSequence[index], incrementSequence[index] == Calendar.DAY_OF_MONTH ? 1 : 0);
        calResult.set(Calendar.MILLISECOND, 0); // we don't deal with sub second resolution

        if (calResult.before(calThen))
            calResult.add(calendarField, 1);

        return calResult.getTime();
    }

    public static Date next(Date then, int calendarField, int minimalDelta) {
        return next(then, calendarField, 1, minimalDelta);
    }

    private static int getIncrementSequenceIndex(int calendarFieldNumber) {
        for (int index = 0; index < incrementSequence.length; ++index)
            if (incrementSequence[index] == calendarFieldNumber)
                return index;

        return 0;
    }
}

Related

  1. nextMonth(Date d)
  2. nextMonth(Date date)
  3. nextMonth(Date date, int month)
  4. nextMonth(final Date date)
  5. nextMonthDateTime(Date date, int month)
  6. nextMonthStart(Date period)