简体   繁体   English

无法设置公历日期和日期

[英]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 我使用哪个数字似乎无关紧要(即,如果我替换了3和9),它总是具有相同的输出

References: 参考文献:

MONTH and DATE are field numbers and aren't the actual value of the fields. MONTHDATE是字段编号,不是字段的实际值。 You should use get() method to get the number set. 您应该使用get()方法来获取数字集。

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: startCalendar.MONTHCalendar.MONTH相同,并且是Calendar类中声明为以下内容的静态字段:

public final static int MONTH = 2;

To get the month from the calendar, you need to call get() : 要从日历中获取月份,您需要调用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 ). 请注意,您应该始终通过声明静态字段的实际类(例如Calendar.MONTH ),而不是引用变量(例如startCalendar.MONTH )和子类(例如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));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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