Search code examples
javadatecalendar

Java: Get month Integer from Date


How do I get the month as an integer from a Date object (java.util.Date)?


Solution

  • java.time (Java 8)

    You can also use the java.time package in Java 8 and convert your java.util.Date object to a java.time.LocalDate object and then just use the getMonthValue() method.

    Date date = new Date();
    LocalDate localDate = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
    int month = localDate.getMonthValue();
    

    Note that month values are here given from 1 to 12 contrary to cal.get(Calendar.MONTH) in adarshr's answer which gives values from 0 to 11.

    But as Basil Bourque said in the comments, the preferred way is to get a Month enum object with the LocalDate::getMonth method.