Calendar.MONTH returns incorrect month

2

I'm developing a method where I can get the date, month, and year to create a security key to connect to the server. But I have already verified the date of my emulator and my cell phone is correct, but the month comes with the previous month.

My code is as follows.

Calendar c = new Calendar.getIntance();
 int ano = c.get(Calendar.YEAR);
 int dia =c.get(Calendar.DAY_OF_MONTH);
 int mes = c.get(Calendar.MONTH);

Has anyone ever had this problem with Calendar ? The year and day are coming correct, only month is coming with a previous month.

    
asked by anonymous 21.10.2016 / 23:56

1 answer

6

According to documentation :

  

Field number for get and set indicating the month. This is a   calendar-specific value. The first month of the year in the Gregorian   and Julian calendars i s JANUARY which is 0 ; the last depends on the   number of months in a year.

Months are indexed from 0 , January, and December, 11 .

To solve, just add 1 :

int mes = c.get(Calendar.MONTH + 1);

The reason why Java uses zero as a bootstrap might be due to this being the C pattern. Java is a C language descendant .

The reason for being zero the initialization base, can be summarized in this Software Engineering response a>:

  

The index in a array is not really an index. It is simply an offset that is the distance from the beginning of array .

     

The first element is at the beginning of array so there is no   distance. Therefore, the offset is zero .

Here has a list that shows which languages use 0 or 1 as the base boot.

More information:

22.10.2016 / 00:14