Java - Date Time Month

Introduction

Month enum has 12 constants to represents the 12 months of the year.

The constant names are JANUARY, FEBRUARY, MARCH, APRIL, MAY, JUNE, JULY, AUGUST, SEPTEMBER, OCTOBER, NOVEMBER, and DECEMBER.

Months are numbered sequentially from 1 to 12, January being 1 and December being 12.

Month enum provides some useful methods

  • of() to get an instance of Month from an int value,
  • from() to get the Month from any date object,
  • getValue() to get the int value of the Month, etc.

The following code demonstrates some uses of the Month enum.

Demo

import java.time.LocalDate;
import java.time.Month;

public class Main {
        public static void main(String[] args) {
                // Use Month.JULY as a method argument
                LocalDate ld1 = LocalDate.of(2012, Month.JULY, 1);

                // Derive a Month from a local date
                Month m1 = Month.from(ld1);

                // Create a Month from an int value 2
                Month m2 = Month.of(2);

                // Get the next month from m2
                Month m3 = m2.plus(1);

                // Get the Month from a local date
                Month m4 = ld1.getMonth();

                // Convert an enum constant to an int
                int m5 = m2.getValue();

                System.out.format("%s, %s, %s, %s, %d%n", m1, m2, m3, m4, m5);
        }/*  www  . ja v  a  2s  .  co  m*/
}

Result