Getting current Year and Month resulting strange results
Solution 1
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.
Solution 2
Note MONTHS starts from 0..So if you need to map it to practical problems just add +1
int month=c.get(Calendar.MONTH)+1;
Solution 3
int year=c.get(Calendar.YEAR);
int month=c.get(Calendar.MONTH);
System.out.println(year);
System.out.println(month);
Solution 4
tl;dr
YearMonth.now(
ZoneId.of( "America/Montreal" )
)
Details
The Answer by Jon Skeet is correct. You were accessing constants rather than interrogating your own object.
Here is an entirely different alternative, using modern date-time classes.
Avoid legacy date-time classes
The old date-time classes such as java.util.Date
, java.util.Calendar
, and java.text.SimpleTextFormat
are now legacy, supplanted by the java.time classes.
YearMonth
If you are focused on the year and month without a date, without a time-of-day, and without a time zone, use the YearMonth
class.
Rather than pass mere integer numbers around for year and for month, pass around objects of this class. Doing so provides type-safety, ensures valid values, and makes your code more self-documenting.
Determining the current year and month means determining the current date. And for that a time zone is crucial. For any given moment, the date varies around the globe by zone.
ZoneId z = ZoneId.of( "America/Montreal" );
YearMonth ym = YearMonth.now( z );
You can interrogate for its parts.
int year = ym.getYear();
int month = ym.getMonthValue();
This class offers handy methods such as telling you if this is a leap year. You can do math, such as adding/subtracting months/years. You can get a date for any day of this year-month. And more.
Month
Rather than mess around with a mere integer for month, I suggest you use the Month
enum. This class has a dozen instances pre-defined, one for each month of the year. As mentioned above, using objects gives you type-safety, valid values, and self-documenting code.
Month m = ym.getMonth();
The class has helpful methods such as generating an localized string with the monthβs name.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
-
Java SE 8 and SE 9 and later
- Built-in.
- Part of the standard Java API with a bundled implementation.
- Java 9 adds some minor features and fixes.
-
Java SE 6 and SE 7
- Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
-
Android
- The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
- See How to useβ¦.
Solution 5
Calendar c= Calendar.getInstance()
int cyear = c.get(Calendar.YEAR);//calender year starts from 1900 so you must add 1900 to the value recevie.i.e., 1990+112 = 2012
int cmonth = c.get(Calendar.MONTH);//this is april so you will receive 3 instead of 4.
int cday = c.get(Calendar.DAY_OF_MONTH);
refer this LINK
Related videos on Youtube
Yaqub Ahmad
My top Answer1, Answer2 on stackoverflow. My top question1, question2 on stackoverflow.
Updated on January 09, 2020Comments
-
Yaqub Ahmad over 4 years
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.
-
Jon Skeet about 12 years@YaqubAhmad: My pleasure - two of the other answers were correct, but I felt they could do with a bit more explanation :)
-
Bala Vishnu over 10 yearsint cmonth = c.get(Calendar.MONTH);//this is april so you will receive 3 instead of 4.
-
Bala Vishnu over 10 yearsThe person who voted down for my result...see this line in the accepted answer...to make it compatible with real month you must add 1..otherwise January will be 0...If u dono understand dont vote...don't -1
-
yohannist over 10 yearsFYI, c.get(Calendar.MONTH) is a zero based index of the months.
-
Basil Bourque over 5 yearsThis terrible Calendar class was supplanted years ago by the java.time classes with the adoption of JSR 310. The modern approach:
LocalDate.now().getMonthValue()
-
Basil Bourque over 5 yearsFor sane numbering, use the modern approach with the java.time classes:
LocalDate.now().getMonthValue()
β 1-12 for January-December.