These classes support limited date information as their names imply. Since they have similar methods we will focus on the MonthDay class. The MonthDay class represents a month and day combination such as August 4. It is immutable and possesses a number of methods to compare or otherwise use instances of this class. It does not contain information regarding the year or time zone. This class is useful when we only need information about a month and day of the month. There are several static methods used to create instances of MonthDay. They include overloaded versions of now, of, and parse. Several of these are illustrated below. With the exception of the first declaration using the now method, these will all create a MonthDay object that represents August 4. MonthDay monthDay = MonthDay.now(); monthDay = MonthDay.of(8, 4); monthDay = MonthDay.of(Month.AUGUST, 4); monthDay = MonthDay.parse(“–08-04”);
The parse method requires a string formatted as “–MM-dd”. If not, it will throw a java.time.format.DateTimeParseException exception. A MonthDay object can also be created using with type methods as illustrated below. This will create a new MonthDay object that is the copy of the first one but the month has been changed to April. The withMonth version has the same effect. monthDay = MonthDay.now(); monthDay = monthDay.with(Month.APRIL); monthDay = monthDay.withMonth(4); The day can be altered using the withDayOfMonth method in a similar fashion. We can create a LocalDate from a MonthDay instance using the atYear method as shown below: LocalDate date = monthDay.atYear(2014); Be careful when using MonthDay objects. A MonthDay of February 29 is considered to be valid. Whether it is actually valid is dependent on the year. However, a date of February 30 is invalid. A minimum check of possible date ranges is checked when specifying the month. The isValidYear method can be used to determine if a MonthDay instance is valid for a specific year. In the next example, a MonthDay object is created for February 29. It is then tested against the years 2012 and 2014. monthDay = MonthDay.of(2, 29); System.out.println(monthDay.isValidYear(2012)); System.out.println(monthDay.isValidYear(2014)); The results will be true for 2012 but false for 2014.