更新时间:2023-01-07 14:00:57
为了给多一点背景:
两者新的GregorianCalendar()
和 Calendar.getInstance()
将给予正确的当前日期初始化的日历和时间。
Both new GregorianCalendar()
and Calendar.getInstance()
will correctly give a calendar initialized at the current date and time.
月
和年
是常量的的的 日历
类。你应该的不的使用它们内经的参考,这使它看起来像他们一个对象的状态的一部分。这是日历
类,访问不同的字段的值设计的一个不幸的一部分,你需要调用 GET
使用一个场号,如图其他答案指定为这些常数之一,
MONTH
and YEAR
are constants within the Calendar
class. You should not use them "via" a reference which makes it look like they're part of the state of an object. It's an unfortunate part of the design of the Calendar
class that to access the values of different fields, you need to call get
with a field number, specified as one of those constants, as shown in other answers:
Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
请注意,该数字月份是基于0,所以在写这篇文章(四月份)的时间的月数为3。
Note that the month numbers are 0-based, so at the time of this writing (in April) the month number will be 3.
这是你的 Java语言设计的一个不幸的一部分可以的通过这种类型的前pressions,而不是引用静态成员(如常量)的唯一通过类型名称。
It's an unfortunate part of the design of the Java language that you can reference static members (such as constants) via expressions of that type, rather than only through the type name.
我的建议:
c.YEAR
给出一个编译时错误 - 你最终会与更清晰code,如果你总是使用 Calendar.YEAR
。c.YEAR
give a compile-time error - you'll end up with much clearer code if you always use Calendar.YEAR
.