Getting current Year and Month resulting strange results
Asked Answered
N

6

28

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.

Niple answered 15/4, 2012 at 11:30 Comment(0)
D
74

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 use Calendar.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.
Draper answered 15/4, 2012 at 11:55 Comment(1)
@YaqubAhmad: My pleasure - two of the other answers were correct, but I felt they could do with a bit more explanation :)Draper
M
23

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;
Melisamelisande answered 8/12, 2013 at 8:34 Comment(3)
int cmonth = c.get(Calendar.MONTH);//this is april so you will receive 3 instead of 4.Melisamelisande
The 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 -1Melisamelisande
For sane numbering, use the modern approach with the java.time classes: LocalDate.now().getMonthValue() ➙ 1-12 for January-December.Nogood
B
5
int year=c.get(Calendar.YEAR);
int month=c.get(Calendar.MONTH);

   System.out.println(year);
   System.out.println(month);
Bunce answered 15/4, 2012 at 11:36 Comment(1)
FYI, c.get(Calendar.MONTH) is a zero based index of the months.Carbajal
N
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
Nogood answered 16/12, 2016 at 3:33 Comment(0)
R
3
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

Rencontre answered 15/4, 2012 at 11:36 Comment(0)
B
2

How to get current Year and Month.

        Calendar calendar = Calendar.getInstance();             
        int month = calendar.get(Calendar.MONTH) + 1;
        int year = calendar.get(Calendar.YEAR);

Very important to add 1 to get the correct month, because the first month value is 0:

        int month = calendar.get(Calendar.MONTH) + 1;

MONTH :Field number for get and set indicating the month. This is a calendar-specific value. The first month of the year in the Gregorian and Julian calendars is JANUARY which is 0; the last depends on the number of months in a year.

Brilliant answered 15/12, 2016 at 19:18 Comment(5)
This terrible Calendar class was supplanted years ago by the java.time classes with the adoption of JSR 310. The modern approach: LocalDate.now().getMonthValue()Nogood
@BasilBourque Call requires API level 26 (current min is 24): java.time.LocalDate#nowHumbuggery
@ARSharifUddinJUMMAN Not quite the case any longer. For earlier versions of Android, you have access to some of the newer classes such as java.time via “desugaring” in the latest tooling. See the official article: Java 8+ APIs available through desugaring.Nogood
@ARSharifUddinJUMMAN change inside your Build,gradle: minSdkVersion 26Brilliant
@BasilBourque Basically, I am designing my project in such a way that Android 7 users can also use it. So I am currently getting date, month and year through Calendar class.Humbuggery

© 2022 - 2024 — McMap. All rights reserved.