Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Just to give a bit more background:</p> <p>Both <code>new GregorianCalendar()</code> and <code>Calendar.getInstance()</code> will correctly give a calendar initialized at the current date and time.</p> <p><code>MONTH</code> and <code>YEAR</code> are <em>constants</em> within the <a href="http://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html" rel="noreferrer"><code>Calendar</code></a> class. You should <em>not</em> 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 <code>Calendar</code> class that to access the values of different fields, you need to call <code>get</code> with a field number, specified as one of those constants, as shown in other answers:</p> <pre><code>Calendar c = Calendar.getInstance(); int year = c.get(Calendar.YEAR); int month = c.get(Calendar.MONTH); </code></pre> <p>Note that the month numbers are 0-based, so at the time of this writing (in April) the month number will be 3.</p> <p>It's an unfortunate part of the design of the Java language that you <em>can</em> reference static members (such as constants) via expressions of that type, rather than <em>only</em> through the type name.</p> <p>My recommendations:</p> <ul> <li>If your IDE allows it (as Eclipse does), make expressions such as <code>c.YEAR</code> give a compile-time error - you'll end up with much clearer code if you always use <code>Calendar.YEAR</code>.</li> <li>Where possible, use <a href="http://www.joda.org/joda-time/" rel="noreferrer">Joda Time</a> - 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.</li> </ul>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload