-3

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 basically 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 returns to me 115 and 116.

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

Andrea
  • 6,032
  • 2
  • 28
  • 55
AndreaNobili
  • 40,955
  • 107
  • 324
  • 596

4 Answers4

7

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));
Bruno
  • 2,889
  • 1
  • 18
  • 25
1

You should use getFullYear(). getYear() simply returns the number of years since 1900.

Andrea
  • 6,032
  • 2
  • 28
  • 55
1

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. Please use Calender class

Rama Krishna
  • 120
  • 8
0

The year value returned from getYear() is the amount of years passed since 1900.

heksesang
  • 171
  • 6