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