获得当前年份和月份导致奇怪的结果 [英] Getting current Year and Month resulting strange results
问题描述
GregorianCalendar gc = new GregorianCalendar();
gc.YEAR //返回1
gc.MONTH //返回2
日历c = Calendar.getInstance();
c.YEAR //返回1
c.MONTH //返回2
只是给一点点背景:
新的GregorianCalendar()
和 Calendar.getInstance()
将正确地给出在当前日期和时间初始化的日历。
MONTH
和 YEAR
是 / em>在 日历
类。你不应该使用它们通过一个引用,使它看起来像是对象状态的一部分。对于访问不同字段的值的 Calendar
类的设计是不幸的一部分,您需要调用 get
一个字段号,指定为其中一个常量,如其他答案所示:
日历c = Calendar.getInstance( );
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
请注意,月份号码为0,所以在撰写本文时(4月份)月份号将为3。
这是Java语言设计的一个不幸的部分,您可以引用静态成员(如常量)通过该类型的表达式,而不是仅通过类型名称 。
我的建议:
- 如果您的IDE允许它(如Eclipse所做),则使表达式(例如
c.YEAR
给出编译时错误 - 如果您始终使用Calendar.YEAR
,则最终会得到更清晰的代码。 - 尽可能使用 Joda时间 - 一个更好的Java日期/时间库。诚然,在Android上,您可能有点空间有限,但如果您的应用程序执行大量的日期/时间操作,那么您将会节省很多麻烦。
I am working on a learning project related to Android. I am trying to get current year & month by using below code but it not works for me.
GregorianCalendar gc = new GregorianCalendar();
gc.YEAR // returning 1
gc.MONTH // returning 2
Calendar c = Calendar.getInstance();
c.YEAR // returning 1
c.MONTH // returning 2
Can someone help me? Am i doing something wrong? please forgive me i am new to java development. thanks.
Just to give a bit more background:
Both new GregorianCalendar()
and Calendar.getInstance()
will correctly give a calendar initialized at the current date and time.
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);
Note that the month numbers are 0-based, so at the time of this writing (in April) the month number will be 3.
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.
My recommendations:
- If your IDE allows it (as Eclipse does), make expressions such as
c.YEAR
give a compile-time error - you'll end up with much clearer code if you always useCalendar.YEAR
. - Where possible, use Joda Time - a much better date/time library for Java. Admittedly on Android you may be a bit space-constrained, but if your app does a lot of date/time manipulation, it would save you a lot of headaches.
这篇关于获得当前年份和月份导致奇怪的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!