Why are months off by one with Java SimpleDateForm

2019-01-19 19:21发布

问题:

I am using SimpleDateFormat to display a Calendar like this :

public String getDate()
{
    String DATE_FORMAT = "EEEE, dd/MM/yyyy HH:mm:ss";
    SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
    System.err.println(date.getTime().getMonth());
    return sdf.format(date.getTime());
}

The shell returns 6 and the display : mardi, 06/07/2010 12:44:52

It can't be possible ? Why ?

Thanks

回答1:

From the Java API:

public int getMonth()

Returns a number representing the month that contains or begins with the instant in time represented by this Date object. The value returned is between 0 and 11, with the value 0 representing January.



回答2:

Unfortunately, months in class Date and class Calendar are zero-based. (In my opinion, this was a huge design mistake in those classes, and it's just one of the many design mistakes in Java's date and time API).

Note that class Calendar has constants to represent the months: Calendar.JANUARY, Calendar.FEBRUARY etc. Use those instead of the raw numbers.

An often mentioned, much better date and time API for Java is Joda Time. Note that there is a proposal to add a new date and time API to the next version of Java that will be based on Joda Time.



回答3:

the getMonth method in Date is 0 indexed. from the JavaDoc:

Returns a number representing the month that contains or begins with the instant in time represented by this Date object. The value returned is between 0 and 11, with the value 0 representing January.



回答4:

month index starts from 0 just like array index



回答5:

that's your locale set to france DD/MM/YY so it is tuesday, July, 2010. the 6th month is july if it starts at 0.