0

Possible Duplicate:
Why does Java’s Date.getYear() return 111 instead of 2011?

I am trying to get the year, month and day form a Date-object, but the following gives me something completely random:

    Date d = new Date();
    System.out.println(d.getYear() + " - " + d.getMonth() + " - " + d.getDay());

I get: 112 - 9 - 1

Does anyone know why? And do you have a bette apporch? For my program i need the Date objects.

Community
  • 1
  • 1
gedemagt
  • 657
  • 1
  • 9
  • 22

3 Answers3

9

Reading the javadoc of these three methods (which are deprecated and thus shouldn't be used, BTW) would tell you why:

  • 112 : number of years since 1900
  • 9: month number, starting from 0 (so 9 means october)
  • 1: day of month

Use a Calendar to get date fields, and a DateFormat to format dates.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
1

Yup... the docs know

Specifically, the year that getYear returns is the current Gregorian year minus 1900.

Further still, those getters are deprecated. You should use the Calendar class.

If you must take Date objects in, then use Calendar.getInstance().setTime(dateObject)

Dancrumb
  • 26,597
  • 10
  • 74
  • 130
1

Source code explains the reason.

@Deprecated
public int getYear() {
    return normalize().getYear() - 1900;
}
@Deprecated
public int getMonth() {
return normalize().getMonth() - 1; // adjust 1-based to 0-based
}

@Deprecated
public int getDay() {
return normalize().getDayOfWeek() - gcal.SUNDAY;
}
chrome
  • 661
  • 2
  • 7
  • 23