Java Data Type How to - Get Month number starting from 0 as January








Question

We would like to know how to get Month number starting from 0 as January.

Answer

import java.util.Calendar;
import java.util.Date;
//from w w w . j  ava  2 s . c om
public class Main {
  public static void main(String[] argv) {
    System.out.println(getMonth(new Date()));
  }

  public static Integer getMonth(Date date) {
    if (date == null)
      return 0;
    Calendar cal = Calendar.getInstance();
    cal.setTime(date);
    return cal.get(Calendar.MONTH);
  }
}

The code above generates the following result.