Calendar returning wrong value for Calendar.MONTH

2019-09-16 19:39发布

问题:

I have a problem with my month

public static void main(String[] args) {
    GregorianCalendar tgl;
    tgl = new GregorianCalendar ();

    System.out.println("Tanggal Sekarang : " +
            tgl.get (Calendar.DATE) + "/" +
            tgl.get (Calendar.MONTH) + "/" +
            tgl.get (Calendar.YEAR));
}

The result is :

Date now : 27/3/2013

回答1:

Calendar.MONTH is zero-based. So April will appear as 3.

Instead, if you want to format a date use SimpleDateFormat and call getTime() on your calendar instance to get a Date:

SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
System.out.println(dateFormat.format(tgl.getTime()));


标签: java calendar