Calendar c = Calendar.getInstance();
c.set(Calendar.MONTH, Calendar.OCTOBER);
c.set(Calendar.DAY_OF_MONTH, 31);
c.set(Calendar.MONTH, c.get(Calendar.MONTH)+1); //Returns Dec 1. Expect Nov 30.
If I have a calendar object and the last day of a month falls on the 31st and the next month has less days than the previous, how can I ensure that by setting the month ahead I will not go beyond the next month?
Use add() instead of set() as the Calendar is "smart" enough to determine the difference of days and such...
public static void main(String[] args) throws Exception {
Calendar c = Calendar.getInstance();
c.set(Calendar.MONTH, Calendar.OCTOBER);
c.set(Calendar.DAY_OF_MONTH, 31);
c.add(Calendar.MONTH, 1);
System.out.println(c.getTime());
}
Output (as of my current run):
Sun Nov 30 09:08:01 EST 2014