Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are months off by one with Java SimpleDateFormat?

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

like image 506
Natim Avatar asked Jun 07 '10 19:06

Natim


2 Answers

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.

like image 60
Daniel Engmann Avatar answered Nov 08 '22 11:11

Daniel Engmann


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.

like image 40
Jesper Avatar answered Nov 08 '22 12:11

Jesper