javadateapache-commonsapache-commons-lang

apache.commons.lang3.DateUtils.setMonths with December


I am facing very strange issue.. Here is the code, which generates a new Date object:

Date result = DateUtils.setYears(new Date(), year);
result = DateUtils.setMonths(result, month);
return DateUtils.setDays(result, day);

If I pass any value for month starting from 1 till 11 - everything works fine, 1 means January, 2 - February ... 11 - November. But with 12 it always fails with java.lang.IllegalArgumentException: MONTH exception..

When I try to pass 0-based values, the first one 0 means December of previous year.. Any ideas?

Thank you in advance


Solution

  • The method setMonths look like

     public static Date setMonths(Date date, int amount) {
            return set(date, Calendar.MONTH, amount);
        }
    

    As you can notice that internally it uses Calendar.MONTH from java. Months in Calendar class starts from 0 till 12(12 value mean UNDECIMBER i.e. thireteenth month of the year Although GregorianCalendar does not use this value, lunar calendars do). So when you are passing 0 it means January, 1 it means February,... and 11 means December. For invalid month value calendar class throw

    java.lang.IllegalArgumentException