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.
Calendar cal = Calendar. getInstance(); Let us now get the current date, year and month.
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.
innerHTML = months[date. getMonth()] + ' ' + date. getFullYear(); };
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:
c.YEAR
give a compile-time error - you'll end up with much clearer code if you always use Calendar.YEAR
.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With