Java MonthDay
The Java MonthDay class is an immutable and thread-safe class that represents the combination of a month and day-of-month. The MonthDay class can be used to store information in the following format “April 22nd”.
How to use
This class does not handle or represent a year, time or time-zone, as it does not maintain a year, the leap day of February 29th is considered valid. Try the following examples to better understand –
At year example
The following example program shows how you can atYear() function with MonthDay.
import java.time.LocalDate; import java.time.MonthDay; public class MonthDayExample1 { public static void main(String[] args) { // Get a instance of MonthDay MonthDay monthDay = MonthDay.now(); System.out.println(monthDay); // At year example LocalDate date = monthDay.atYear(1990); System.out.println(date); } }
Valid year example
The following example program shows how you can check year is valid or not.
import java.time.MonthDay; public class MonthDayExample2 { public static void main(String[] args) { // Get a instance of MonthDay MonthDay monthDay = MonthDay.now(); // Is valid year? System.out.println(monthDay.isValidYear(2019)); } }
Fields example
The following example program shows how you can get different fields.
import java.time.MonthDay; import java.time.temporal.ChronoField; public class MonthDayExample3 { public static void main(String[] args) { // Get a instance of MonthDay MonthDay monthDay = MonthDay.now(); // Get day of month int dayOfMonth = monthDay.get(ChronoField.DAY_OF_MONTH); System.out.println(dayOfMonth); // Get month of year int monthOfYear = monthDay.get(ChronoField.MONTH_OF_YEAR); System.out.println(monthOfYear); } }