Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 587
karlgrz Avatar asked Sep 25 '08 21:09

karlgrz


People also ask

How do you find the year of a date object?

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.

How do you find the year in a string?

Calendar now = Calendar. getInstance(); DateFormat date = new SimpleDateFormat("yyyy"); String year = date. format(now);


2 Answers

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?)

like image 131
cagcowboy Avatar answered Oct 11 '22 18:10

cagcowboy


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();
like image 183
assylias Avatar answered Oct 11 '22 17:10

assylias