johngoche9999 johngoche9999 - 5 months ago 27
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());
System.out.println(this.sale.getSaleDate().getYear());
System.out.println(this.sale.getSaleDate().getMonth());
System.out.println(this.sale.getSaleDate().getDate());


returns

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
java.util.Date
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

According to javadocs:

@Deprecated
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.