Search code examples
javacalendar

Calendar class time month not matching


Calendar c = Calendar.getInstance();

System.out.println("Mili->>" + c.getTimeInMillis());

System.out.println("Month  ->>" + Calendar.MONTH);

Though I am getting correct time in millisec format, Month is showing as 2 (March??) Why so?

Below is output

Mili->>1434029840778

Month ->>2


Solution

  • What you want is the following idiom: c.get(Calendar.MONTH).

    Calendar.MONTH per se is just an internal constant and will (hopefully) always return 2.

    Example

    // We're in June at the time of writing
    // Months are 0-based so June == 5
    Calendar c = Calendar.getInstance();
    System.out.println(Calendar.MONTH);
    System.out.println(c.get(Calendar.MONTH));
    

    Output

    2
    5
    

    See also: API