views:

7690

answers:

6

I need to determine the current year in Java as an integer. I would like to be able to use this value as a counter that I can, for example, use to run from now until a specified year in the past (i.e. my value starts at 2008, and I have a "firstYearOfData" value that is set to 1994. I can now run my process from 2008 back to 1994). I could just use java.util.Date(), but it is deprecated.

+6  A: 
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?)

cagcowboy
Upon seeing your answer, Calendar would be a fine object to use. I was looking for a one-liner and I didn't think Calendar would have that for me. Proven wrong I am! Thanks!
KG
A: 

The easiest way is to get the year from Calendar.

// year is stored as a static member
int year = Calendar.getInstance().get(Calendar.YEAR);
conmulligan
Calendar.YEAR is not the current year.
toolkit
Calendar.YEAR is defined thus... public final static int YEAR = 1;
cagcowboy
The get() API on Calendar gets the datum that is at the field specified by the constant. The year is located in the 1's field in the Calendar object! Calendar.getInstance() is getting the current date.http://java.sun.com/j2se/1.4.2/docs/api/java/util/Calendar.html#get(int)
Bob King
+3  A: 

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

toolkit
+1  A: 

If your application is making heavy use of Date and Calendar objects, you really should use Joda Time, because java.util.Date is mutable. java.util.Calendar has performance problems when its fields get updated, and is clunky for datetime arithmetic.

Alan
A: 

I use special functions in my library to work with days/month/year ints -

int[] int_dmy( long timestamp ) // remember month is [0..11] !!!
{
  Calendar cal = new GregorianCalendar(); cal.setTimeInMillis( timestamp );
  return new int[] { 
    cal.get( Calendar.DATE ), cal.get( Calendar.MONTH ), cal.get( Calendar.YEAR )
  };
};


int[] int_dmy( Date d ) { 
 ...
}
maxp
+1  A: 

You can do the whole thing using Integer math without needing to instantiate a calendar:

return (System.currentTimeMillis()/1000/3600/24/365.25 +1970);

May be off for an hour or two at new year but I don't get the impression that is an issue?

Ewan Makepeace