I need to determine the current year in Java as an integer. I could just use java.util.Date()
, but it is deprecated.
The getYear() method is used to get the year of a given date according to local time. The getYear() method returns the year minus 1900; thus: * For years above 2000, the value returned by getYear() is 100 or greater. For example, if the year is 2009, getYear() returns 109.
Calendar now = Calendar. getInstance(); DateFormat date = new SimpleDateFormat("yyyy"); String year = date. format(now);
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();
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