Distopic
Distopic

Reputation: 737

Calendar.MONTH and internal working

I have a little question about internal java working and Calendar, i dont understand why when i use for example:

    Calendar c = Calendar.getInstance();
    mesInt = c.get(Calendar.MONTH); 
    System.out.println(mesInt);

If then i print mesInt, if the actually month is february i obtain mesInt = 1;

is there any special reason for that? I would like to know because i had problems before with my database, and i would like if it is possible to know the solution of start by 0 the month.

Thanks for all, and sorry if the questions is duplicated i haven not found it.

PD: i know that is zero-based, but i would like to know the real reason for that.

PD2: sry for my bad english. I know the solution i would like to know the reason of that.

Upvotes: 0

Views: 131

Answers (5)

yonathaniel
yonathaniel

Reputation: 1

I bet it's for the same reason array indices start from 0. It's just how it is. February is often displayed as "2", but displaying or printing values is different from using them in code.

Upvotes: 0

Peter Lawrey
Peter Lawrey

Reputation: 533530

The documentation states the first month is 0.

i would like to know the real reason for that.

I suspect starting at 0 is easier to calculate. I am not sure any one person will admit to designing Calendar. Perhaps it made sense at the time as many of the numberings for years, AM/PM etc start at 0. BTW days of the week start at 1.

know i would like if it is possible to know the solution.

Use

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

BTW For me the strange one is UNIDECIMBER when uni-deci mean 11 not 13.

Upvotes: 4

Saikat
Saikat

Reputation: 558

The Specification of Calendar.MONTH is as follows:

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.

Essentially for all practical purposes : January is 0 and December is 11.

Upvotes: 0

nkukhar
nkukhar

Reputation: 2025

Months in Calendar starts from zero it means that January -> 0 February -> 1 etc.

Upvotes: 0

Eric
Eric

Reputation: 1297

Months are 0 based. I'm not sure of the reason why...

So when using either get or set with month you need to remember to either +1 or -1 as required.

Calendar c = Calendar.getInstance();
int mesInt = c.get(Calendar.MONTH) + 1;
c.set(Calendar.MONTH, mesInt - 1);

Upvotes: 0

Related Questions