johngoche9999 johngoche9999 - 2 years ago 229
Java Question

java.util.Date and getYear()

I am having the following problem in Java (I see some people are having
a similar problem in JavaScript but I'm using Java)

System.out.println(new Date().getYear());
System.out.println(new GregorianCalendar().getTime().getYear());


I/System.out( 4274): 112
I/System.out( 4274): 112
I/System.out( 4274): 112
I/System.out( 4274): 1
I/System.out( 4274): 11

I don't understand the 112 bit which I thought would have been 2012.
What's going on? Is the
class unusable? I am storing this as a field in several
of my classes to store a date and time. What should I do?

Answer Source

According to javadocs:

public int getYear()

Deprecated. As of JDK version 1.1, replaced by Calendar.get(Calendar.YEAR) - 1900.

Returns a value that is the result of subtracting 1900 from the year that contains or begins with the instant in time represented by this Date object, as interpreted in the local time zone.

Returns: the year represented by this date, minus 1900.

See Also: Calendar

So 112 is the correct output. I would follow the advice in the Javadoc or use JodaTime instead.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download