TimeToCodeTheRoad
TimeToCodeTheRoad

Reputation: 7312

Calendar class java

I am setting the value to be 23 January 2009, but when I ask for month it returns '2' Here is my code:

Calendar calendar=GregorianCalendar.getInstance();  
calendar.set(2009,01,23);  
calendar.getTime();  
System.out.println(calendar.MONTH);  

Please help! I expect the first output to be 1, not 2!

Upvotes: 1

Views: 465

Answers (4)

Basil Bourque
Basil Bourque

Reputation: 338276

tl;dr

java.time.LocalDate.of( 2009 , Month.JANUARY , 23 )

Details

In addition to correct Answer by JB Nizet, I have more points.

Octal number

,01,

Your leading zero makes a numeric literal in octal (base 8) rather than decimal (base 10). Not likely what you intended.

java.time

You are using terribly flawed date-time classes that were supplanted by the modern java.time classes defined in JSR 310.

For a date-only value without time-of-day and without time zone or offset, use LocalDate.

Unlike the legacy class, java.time uses sane numbering. So months are 1-12 for January-December.

LocalDate ld = LocalDate.of( 2009 , 1 , 23 ) ;

Even better, use Month constant for clarity.

LocalDate ld = LocalDate.of( 2009 , Month.JANUARY , 23 ) ;

Upvotes: 0

Stefan
Stefan

Reputation: 4705

You need to use

calendar.get(Calendar.MONTH)

get the month of the currently set date in your calendar instance. Calendar.MONTH (which you accessed via the instance) is just a constant which tells the get() to return the month.

See JavaDoc for more information: http://docs.oracle.com/javase/1.4.2/docs/api/java/util/Calendar.html

Upvotes: 1

JB Nizet
JB Nizet

Reputation: 691645

Calendar.MONTH is a constant. It's used to indicate that you want the month field, using calendar.get():

System.out.println(calendar.get(Calendar.MONTH));

Upvotes: 7

Tomasz Nurkiewicz
Tomasz Nurkiewicz

Reputation: 340713

Months are 0-based in Calendar, you must write:

calendar.set(2009, 0, 23);

...or better, to avoid confusion:

calendar.set(2009, Calendar.JANUARY, 23);

Upvotes: 4

Related Questions