AndreaNobili AndreaNobili - 14 days ago 7
Java Question

Why the getYear() of Java Date class returns a wrong value?

I am working on a Java application and I have some problem trying to obtain the value of the year from a Date object.

So bascally I have the following situation:

Basically into my code I have:

Date datePrimoVersamento = sdf.parse(mappaQuote.get(1).getDatariferimentoprezzo());
Date dateMovimentoFinale = sdf.parse(mappaQuote.get(0).getDatariferimentoprezzo());

System.out.println("datePrimoVersamento: " + datePrimoVersamento + " year: " + datePrimoVersamento.getYear());
System.out.println("dateMovimentoFinale: " + " year: " + dateMovimentoFinale.getYear());


The output is:

datePrimoVersamento: Fri Nov 27 00:00:00 CET 2015 year: 115
dateMovimentoFinale: Mon Oct 31 00:00:00 CET 2016 year: 116


As you can see the year of the 2 dates are 2015 an 2016 but the getYear() method return to me 115 and 116.

Why? How is it possible? How can I fix this issue?

Answer

From the Javadoc:

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.

So: 2016 - 1900 = 116 and 2015 - 1900 = 115.

You should try this:

Calendar cal = Calendar.getInstance();
cal.setTime(datePrimoVersamento );
System.out.println("datePrimoVersamento's Year: " + cal.get(Calendar.YEAR));
cal.setTime(dateMovimentoFinale );
System.out.println("dateMovimentoFinale's Year: " + cal.get(Calendar.YEAR));