简体   繁体   中英

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!

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));

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);

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM