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.
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?)
The easiest way is to get the year from Calendar.
// year is stored as a static member
int year = Calendar.getInstance().get(Calendar.YEAR);
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
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.
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 ) {
...
}
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?