Get integer value of the current year in Java

I need to determine the current year in Java as an integer. I could just use java.util.Date(), but it is deprecated.


int year = Calendar.getInstance().get(Calendar.YEAR);

Not sure if this meets with the criteria of not setting up a new Calendar? (Why the opposition to doing so?)


Using Java 8's time API (assuming you are happy to get the year in your system's default time zone), you could use the Year::now method:

int year = Year.now().getValue();

This simplest (using Calendar, sorry) is:

 int year = Calendar.getInstance().get(Calendar.YEAR);

There is also the new Date and Time API JSR, as well as Joda Time


You can also use 2 methods from java.time.YearMonth( Since Java 8 ):

import java.time.YearMonth;
...
int year = YearMonth.now().getYear();
int month = YearMonth.now().getMonthValue();

The easiest way is to get the year from Calendar.

// year is stored as a static member
int year = Calendar.getInstance().get(Calendar.YEAR);