views:

143

answers:

6

Hello,

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  A: 

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.

akf
+10  A: 

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.

Daniel Engmann
A: 

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.

Marc
+2  A: 

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.

Jesper
Java inherited that design mistake from POSIX, I believe. Originally intended to allow the month value to be used as an index into an array of month names.
Michael Borgwardt
+1  A: 

month index starts from 0 just like array index

HZhang