简体   繁体   中英

Unable to set GregorianCalendar Month and Date

Im trying to set the month and date of a Gregorian Calendar:

GregorianCalendar startCalendar = new GregorianCalendar();

startCalendar.set(GregorianCalendar.MONTH, 3);
System.out.println(startCalendar.MONTH);
startCalendar.set(GregorianCalendar.DATE, 9);
System.out.println(startCalendar.DATE);

The output is:

2
5

It doesn't seem to matter which numbers i use (ie. if i replace the 3 and 9), it always has the same output

References:

MONTH and DATE are field numbers and aren't the actual value of the fields. You should use get() method to get the number set.

GregorianCalendar startCalendar = new GregorianCalendar();

startCalendar.set(GregorianCalendar.MONTH, 3);
System.out.println(startCalendar.get(GregorianCalendar.MONTH));
startCalendar.set(GregorianCalendar.DATE, 9);
System.out.println(startCalendar.get(GregorianCalendar.DATE));

startCalendar.MONTH is the same as Calendar.MONTH , and is a static field declared in the Calendar class as:

public final static int MONTH = 2;

To get the month from the calendar, you need to call get() :

startCalendar.get(Calendar.MONTH)

Note that you should always qualify static fields by the actual class declaring them (eg Calendar.MONTH ), never by a reference variable (eg startCalendar.MONTH ) and never by subclass (eg GregorianCalendar.MONTH ).

So, your code should be:

GregorianCalendar startCalendar = new GregorianCalendar();

startCalendar.set(Calendar.MONTH, 3);
System.out.println(startCalendar.get(Calendar.MONTH));
startCalendar.set(Calendar.DATE, 9);
System.out.println(startCalendar.get(Calendar.DATE));

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