Unable to set GregorianCalendar Month and Date

房东的猫 提交于 2020-01-07 02:43:05

问题


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


回答1:


References:

  • GregorianCalendar (Java Platform SE 8 )
  • Calendar (Java Platform SE 8 )

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



回答2:


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 (e.g. Calendar.MONTH), never by a reference variable (e.g. startCalendar.MONTH) and never by subclass (e.g. 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));


来源:https://stackoverflow.com/questions/36110408/unable-to-set-gregoriancalendar-month-and-date

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!