-5

I have some problem trying to create a Date in Java, starting from the year, the month and the day.

So, I have created this simple utility method that creates my date:

private Date creaDataNascita(int birthYear, int birthMonth, int birthDay) {

    Date dataNascita = new Date(birthYear, birthMonth, birthDay);

    return dataNascita;

}

I have the following values for the input parameters (I checked it with the debugger.):

birthYear = 1984
birthMonth = 4
birthDay = 12

The problem is that this line:

Date dataNascita = new Date(birthYear, birthMonth, birthDay);

creates me a strange date, its value in fact is: 12-mag-3884.

Why? What is wrong? What am I missing? How can I fix this issue?

Dimitar
  • 4,402
  • 4
  • 31
  • 47
AndreaNobili
  • 40,955
  • 107
  • 324
  • 596

3 Answers3

3

The Date Javadoc notes

  • A year y is represented by the integer y - 1900.
  • A month is represented by an integer from 0 to 11; 0 is January, 1 is February, and so forth; thus 11 is December.

To get the correct Date with the deprecated Date constructor, it would need to be something like new Date(birthYear - 1900, birthMonth - 1, birthDay); but I would prefer LocalDate like

int birthYear = 1984;
int birthMonth = 4;
int birthDay = 12;
LocalDate ld = LocalDate.of(birthYear, birthMonth, birthDay);
System.out.println(ld);

Output is

1984-04-12
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
-1

As said in the javadoc :

  1. Date(int year, int month, int day) Deprecated. instead use the constructor Date(long date)
  2. Date(long date) Constructs a Date object using the given milliseconds time value.
Aeldred
  • 314
  • 2
  • 15
-1

As referenced in https://docs.oracle.com/javase/8/docs/api/java/util/Date.html,

The Date class is deprecated, Use Calendar.set instead.

Peixiang Zhong
  • 419
  • 4
  • 8
  • What does it being deprecated have to do with the value it produces? Is the value random? – Savior Apr 11 '16 at 13:51
  • 1
    The `java.util.Date` class is *not* deprecated. Many of its methods and constructors are, but the class itself is not. – Ian McLaird Apr 11 '16 at 14:01