Search code examples
javacalendar

February in Java Calendar


I have a problem, I think that the result of this block of code should be "February", but the result is "March", what I'm doing wrong?

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

public class Calendario {

        public static void main(String args[]){
            Locale locale = new Locale("es","MX");
            Calendar calendarTemp = new GregorianCalendar();
            calendarTemp.set(Calendar.MONTH,1);
            String mesTemp = calendarTemp.getDisplayName(Calendar.MONTH, Calendar.LONG, locale);
            System.out.println(mesTemp);

        }

}

Thanks for your help.


Solution

  • Did you try using clear before set? Like this:

    Locale locale = new Locale("es","MX");
    Calendar calendarTemp = new GregorianCalendar();
    calendarTemp.clear(); //add this line
    calendarTemp.set(Calendar.MONTH,1);
    

    I tested and the result is "February".

    Regards.