February on Java Calendar

I have a problem, I think the result of this code block should be “February”, but the result is “March”, what am I 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);

        }

}

Thank you for your help.

+4
source share
3 answers

Have you tried using clear before typing? 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 was February.

Sincerely.

+3
source

I assume February 30th will return as March 2nd.

This duplicate question has a better answer: Strange behavior from java.util.Calendar in February

+4
source

Today is June 30th, and you never set the day of the month in your code, so the 30th is assumed. Since February, less than 30 days, it overflows, and you finish in March. Try the code below and note that setting the day of the month affects the displayed text:

calendarTemp.set(Calendar.MONTH, 1);
calendarTemp.set(Calendar.DAY_OF_MONTH, 1);

As a note, this makes the code more readable for using constants from a class Calendar, for example. Calendar.FEBRUARYinstead of magic numbers, especially because months are based on 0 ...

+3
source

Source: https://habr.com/ru/post/1546613/


All Articles