Java GregorianCalendar What am I doing wrong? Invalid date?

Hello, I have a problem with GregorianCalendar.

What is wrong there?

What is the result of 2010/6/1, not 2010/05/31?

package test;

import java.util.Calendar;
import java.util.GregorianCalendar;

public class Main {

    public static void main(String[] args) {
        Calendar cal = new GregorianCalendar(2010, 5, 31);
        System.out.println(cal.get(Calendar.YEAR) + "/" + cal.get(Calendar.MONTH) + "/" + cal.get(Calendar.DAY_OF_MONTH));
    }

}
+5
source share
3 answers

Java has months from 0, so June 5th. Always use constants. Therefore, I would write:

Calendar cal = new GregorianCalendar(2010, Calendar.MAY, 31);

The same goes for printing your calendar. If you do cal.get(Calendar.MONTH), you get the value 6, JULY.

+9
source

This is because the month number is based on zero, so you are trying to set June 31, but only 30 days in June, so it will be converted to July 1.

+1
source

Toadd , , 31- , , Calendar.setLenient - true.

+1

All Articles