Pergunta

I wrote this following java code to format the date and time in specific formats. You can see the below code at ideone .

import java.util.Calendar;
import java.util.GregorianCalendar;
import java.text.SimpleDateFormat;
class timeAndDateTransformation{
    public static void main(String[] argv){
            Calendar newDate = new GregorianCalendar(2009,7,1,15,20,00);
            SimpleDateFormat dateFormant = new SimpleDateFormat("yyyy/MM/dd");
            SimpleDateFormat timeFormant = new SimpleDateFormat("HH:mm:ss");
            System.out.println(dateFormant.format(newDate.getTime()).toString());
            System.out.println(timeFormant.format(newDate.getTime()).toString());
    }

}

Its giving me following output:

2009/08/01
15:20:00

In this output rest all it perfectly okay, except the month. I passed 7 as a month but in this for-matter output its giving 8 as a output. Please point me where am i doing wrong. I am not very familiar with the date/calendar classes of java, so please bear with me.

Foi útil?

Solução

Months are 0-based, you passed in 7 so that resolves to August.

From the api docs for java.util.Date:

A month is represented by an integer from 0 to 11; 0 is January, 1 is February, and so forth; thus 11 is December.

It's really counter-intuitive to make the month zero-based. I think we've all gotten burned by that one at some point.

Outras dicas

The month field in Java is zero based. GregorianCalendar.JANUARY is 0...etc etc. Therefore, if you want to pass in a date into the constructor, add one to the month value.

If you look at the [JavaDoc here][1], it explains it for you.

[1]: http://download.oracle.com/javase/1.4.2/docs/api/java/util/Calendar.html#set(int, int, int)

Humans like to see the first month (January) being 1, so that's what SimpleDateFormat does.

However computers like to see things starting from 0, and that's how GregorianCalendar manages the month param. See the constructors for GregorianCalendar and the description of the month parameter.

[Java considers January month 0. ][1] But when you output the month number with SimpleDateFormat it uses the standard January is month 1 system. So month 7 is outputted as 8.

If you are having trouble with the JDK's date and calendar consider using Joda Time, it's much easier

[1]: http://download.oracle.com/javase/1.4.2/docs/api/java/util/GregorianCalendar.html#GregorianCalendar(int, int, int)

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top