Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting current Year and Month resulting strange results

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.

like image 658
Yaqub Ahmad Avatar asked Apr 15 '12 11:04

Yaqub Ahmad


People also ask

How to get current date month and year in java?

Calendar cal = Calendar. getInstance(); Let us now get the current date, year and month.

How to get current month and year in android?

To get Current month and then populate the data from db (ex. Current month is January then populate the January data from db, if current month is April then populate the April data from data ) for every months.

How do I get the current month and year in HTML?

innerHTML = months[date. getMonth()] + ' ' + date. getFullYear(); };


1 Answers

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.
like image 55
Jon Skeet Avatar answered Oct 21 '22 08:10

Jon Skeet