Calendar.MONTH returns incorrect month

Asked

Viewed 395 times

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. Only I already checked the date of my emulator and my mobile phone is correct, but the month comes with 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 been through this problem with the Calendar? The year and day is coming right, only the month is coming with a previous month.

1 answer

6


According to the 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 is JANUARY which is 0; the last depends on the number of months in a year.

The months are indexed from 0, January, and December, 11.

To solve, just add 1:

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

Why Java to use zero as the boot base maybe it’s because that’s the default of C. Java is a descending language of C.

The reason to be zero the boot base, can be summarized in that Software Engineering response:

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

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

Here has a list showing which languages they use 0 or 1 as a boot basis.

More information:

Browser other questions tagged

You are not signed in. Login or sign up in order to post.