Java Month Enum
The Month is an immutable and thread-safe enum that represents 12 months of the year – January, February, March, April, May, June, July, August, September, October, November, and December.
How to use
The Month enum can be used to represent month-of-year, like – April. It is a good practice to use enum in applications rather than the int value to ensure the code clarity. Try the following examples to better understand –
Current month example
The following example program shows how you can use Month enum with LocalDate to print current month.
import java.time.LocalDate; import java.time.Month; public class MonthExample1 { public static void main(String[] args) { // Get instance of LocalDate LocalDate localDate = LocalDate.now(); // Get current month using localDate Month month = Month.from(localDate); System.out.println(month); } }
All months example
The following example program shows how you can use Month enum to print all the months.
import java.time.Month; public class MonthExample2 { public static void main(String[] args) { // Get all the months Month[] months = Month.values(); // Print every month for (Month month : months) { System.out.println(month); } } }
Add/Subtract example
The following example program shows how you can plus/minus months with Month enum.
import java.time.Month; public class MonthExample3 { public static void main(String[] args) { // Get month by month number Month month = Month.of(1); // 1 = JANUARY System.out.println(month); // Add 5 months month = month.plus(5); // JANUARY + 5 = JUNE System.out.println(month); // Subtract 2 months month = month.minus(2); // JUNE - 2 = APRIL System.out.println(month); } }
Total days example
The following example program shows how you can use Month enum to get the total number of days in the month.
import java.time.LocalDate; import java.time.Month; import java.time.Year; public class MonthExample4 { public static void main(String[] args) { // Get instance of LocalDate LocalDate localDate = LocalDate.now(); // Use localDate to get month Month month = Month.from(localDate); // Get leap year using isLeap() of Year boolean isLeapYear = Year.isLeap(localDate.getYear()); // Total no of days in month int totalDays = month.length(isLeapYear); System.out.println(String.format("Total days in %s is %d", month.toString(), totalDays)); } }