Date() object inconsistency

Right now is 3/15/11 and when I'm calling a new date object:

Date now = new Date();

I'm getting in return the month as 2 (getMonth()), the day as 2 (getDay()) and the year (getYear()) as 111. Is there a reason for this convention?


Straight from the class's documentation:

  • 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.
  • A date (day of month) is represented by an integer from 1 to 31 in the usual manner.
  • And as for getDay() :

    Returns the day of the week represented by this date. The returned value (0 = Sunday, 1 = Monday, 2 = Tuesday, 3 = Wednesday, 4 = Thursday, 5 = Friday, 6 = Saturday) represents the day of the week that contains or begins with the instant in time represented by this Date object, as interpreted in the local time zone.

    March 15th 2011 is in fact a Tuesday.


    Is there a reason for this convention?

    The reason is that it is what the javadoc for Date specifies; see @matt b's answer.

    The Date APIs were created in the days of JDK 1.0, and are well known to be problematic in a number of areas. That is why most of the Date methods are marked as Deprecated. (By the way, that means that it is recommended that you don't use them in new code!!)

    The Calendar APIs are a significant improvement on Date , but the best by far APIs for handling date / time values in Java are the 3rd-party Joda time APIs.


    If you want examples of Joda time usage, look at the link above. There's an example of Calendar usage in the GregorianCalendar javadocs. More examples of Calendar usage may be found on this page.

    链接地址: http://www.djcxy.com/p/36716.html

    上一篇: 我如何将日期对象转换为日历对象

    下一篇: Date()对象不一致