1 /*
  2  * Copyright (c) 2012, 2023, Oracle and/or its affiliates. All rights reserved.
  3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  4  *
  5  * This code is free software; you can redistribute it and/or modify it
  6  * under the terms of the GNU General Public License version 2 only, as
  7  * published by the Free Software Foundation.  Oracle designates this
  8  * particular file as subject to the "Classpath" exception as provided
  9  * by Oracle in the LICENSE file that accompanied this code.
 10  *
 11  * This code is distributed in the hope that it will be useful, but WITHOUT
 12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 14  * version 2 for more details (a copy is included in the LICENSE file that
 15  * accompanied this code).
 16  *
 17  * You should have received a copy of the GNU General Public License version
 18  * 2 along with this work; if not, write to the Free Software Foundation,
 19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 20  *
 21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 22  * or visit www.oracle.com if you need additional information or have any
 23  * questions.
 24  */
 25 
 26 /*
 27  * This file is available under and governed by the GNU General Public
 28  * License version 2 only, as published by the Free Software Foundation.
 29  * However, the following notice accompanied the original version of this
 30  * file:
 31  *
 32  * Copyright (c) 2007-2012, Stephen Colebourne & Michael Nascimento Santos
 33  *
 34  * All rights reserved.
 35  *
 36  * Redistribution and use in source and binary forms, with or without
 37  * modification, are permitted provided that the following conditions are met:
 38  *
 39  *  * Redistributions of source code must retain the above copyright notice,
 40  *    this list of conditions and the following disclaimer.
 41  *
 42  *  * Redistributions in binary form must reproduce the above copyright notice,
 43  *    this list of conditions and the following disclaimer in the documentation
 44  *    and/or other materials provided with the distribution.
 45  *
 46  *  * Neither the name of JSR-310 nor the names of its contributors
 47  *    may be used to endorse or promote products derived from this software
 48  *    without specific prior written permission.
 49  *
 50  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 51  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 52  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 53  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 54  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 55  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 56  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 57  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 58  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 59  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 60  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 61  */
 62 package java.time;
 63 
 64 import static java.time.temporal.ChronoField.DAY_OF_MONTH;
 65 import static java.time.temporal.ChronoField.MONTH_OF_YEAR;
 66 
 67 import java.io.DataInput;
 68 import java.io.DataOutput;
 69 import java.io.IOException;
 70 import java.io.InvalidObjectException;
 71 import java.io.ObjectInputStream;
 72 import java.io.Serializable;
 73 import java.time.chrono.Chronology;
 74 import java.time.chrono.IsoChronology;
 75 import java.time.format.DateTimeFormatter;
 76 import java.time.format.DateTimeFormatterBuilder;
 77 import java.time.format.DateTimeParseException;
 78 import java.time.temporal.ChronoField;
 79 import java.time.temporal.Temporal;
 80 import java.time.temporal.TemporalAccessor;
 81 import java.time.temporal.TemporalAdjuster;
 82 import java.time.temporal.TemporalField;
 83 import java.time.temporal.TemporalQueries;
 84 import java.time.temporal.TemporalQuery;
 85 import java.time.temporal.UnsupportedTemporalTypeException;
 86 import java.time.temporal.ValueRange;
 87 import java.util.Objects;
 88 
 89 /**
 90  * A month-day in the ISO-8601 calendar system, such as {@code --12-03}.
 91  * <p>
 92  * {@code MonthDay} is an immutable date-time object that represents the combination
 93  * of a month and day-of-month. Any field that can be derived from a month and day,
 94  * such as quarter-of-year, can be obtained.
 95  * <p>
 96  * This class does not store or represent a year, time or time-zone.
 97  * For example, the value "December 3rd" can be stored in a {@code MonthDay}.
 98  * <p>
 99  * Since a {@code MonthDay} does not possess a year, the leap day of
100  * February 29th is considered valid.
101  * <p>
102  * This class implements {@link TemporalAccessor} rather than {@link Temporal}.
103  * This is because it is not possible to define whether February 29th is valid or not
104  * without external information, preventing the implementation of plus/minus.
105  * Related to this, {@code MonthDay} only provides access to query and set the fields
106  * {@code MONTH_OF_YEAR} and {@code DAY_OF_MONTH}.
107  * <p>
108  * The ISO-8601 calendar system is the modern civil calendar system used today
109  * in most of the world. It is equivalent to the proleptic Gregorian calendar
110  * system, in which today's rules for leap years are applied for all time.
111  * For most applications written today, the ISO-8601 rules are entirely suitable.
112  * However, any application that makes use of historical dates, and requires them
113  * to be accurate will find the ISO-8601 approach unsuitable.
114  * <p>
115  * This is a <a href="{@docRoot}/java.base/java/lang/doc-files/ValueBased.html">value-based</a>
116  * class; programmers should treat instances that are
117  * {@linkplain #equals(Object) equal} as interchangeable and should not
118  * use instances for synchronization, or unpredictable behavior may
119  * occur. For example, in a future release, synchronization may fail.
120  * The {@code equals} method should be used for comparisons.
121  *
122  * @implSpec
123  * This class is immutable and thread-safe.
124  *
125  * @since 1.8
126  */
127 @jdk.internal.ValueBased
128 @jdk.internal.MigratedValueClass
129 public final class MonthDay
130         implements TemporalAccessor, TemporalAdjuster, Comparable<MonthDay>, Serializable {
131 
132     /**
133      * Serialization version.
134      */
135     @java.io.Serial
136     private static final long serialVersionUID = -939150713474957432L;
137     /**
138      * Parser.
139      */
140     private static final DateTimeFormatter PARSER = new DateTimeFormatterBuilder()
141         .appendLiteral("--")
142         .appendValue(MONTH_OF_YEAR, 2)
143         .appendLiteral('-')
144         .appendValue(DAY_OF_MONTH, 2)
145         .toFormatter();
146 
147     /**
148      * The month-of-year, not null.
149      */
150     private final int month;
151     /**
152      * The day-of-month.
153      */
154     private final int day;
155 
156     //-----------------------------------------------------------------------
157     /**
158      * Obtains the current month-day from the system clock in the default time-zone.
159      * <p>
160      * This will query the {@link Clock#systemDefaultZone() system clock} in the default
161      * time-zone to obtain the current month-day.
162      * <p>
163      * Using this method will prevent the ability to use an alternate clock for testing
164      * because the clock is hard-coded.
165      *
166      * @return the current month-day using the system clock and default time-zone, not null
167      */
168     public static MonthDay now() {
169         return now(Clock.systemDefaultZone());
170     }
171 
172     /**
173      * Obtains the current month-day from the system clock in the specified time-zone.
174      * <p>
175      * This will query the {@link Clock#system(ZoneId) system clock} to obtain the current month-day.
176      * Specifying the time-zone avoids dependence on the default time-zone.
177      * <p>
178      * Using this method will prevent the ability to use an alternate clock for testing
179      * because the clock is hard-coded.
180      *
181      * @param zone  the zone ID to use, not null
182      * @return the current month-day using the system clock, not null
183      */
184     public static MonthDay now(ZoneId zone) {
185         return now(Clock.system(zone));
186     }
187 
188     /**
189      * Obtains the current month-day from the specified clock.
190      * <p>
191      * This will query the specified clock to obtain the current month-day.
192      * Using this method allows the use of an alternate clock for testing.
193      * The alternate clock may be introduced using {@link Clock dependency injection}.
194      *
195      * @param clock  the clock to use, not null
196      * @return the current month-day, not null
197      */
198     public static MonthDay now(Clock clock) {
199         final LocalDate now = LocalDate.now(clock);  // called once
200         return MonthDay.of(now.getMonth(), now.getDayOfMonth());
201     }
202 
203     //-----------------------------------------------------------------------
204     /**
205      * Obtains an instance of {@code MonthDay}.
206      * <p>
207      * The day-of-month must be valid for the month within a leap year.
208      * Hence, for February, day 29 is valid.
209      * <p>
210      * For example, passing in April and day 31 will throw an exception, as
211      * there can never be April 31st in any year. By contrast, passing in
212      * February 29th is permitted, as that month-day can sometimes be valid.
213      *
214      * @param month  the month-of-year to represent, not null
215      * @param dayOfMonth  the day-of-month to represent, from 1 to 31
216      * @return the month-day, not null
217      * @throws DateTimeException if the value of any field is out of range,
218      *  or if the day-of-month is invalid for the month
219      */
220     public static MonthDay of(Month month, int dayOfMonth) {
221         Objects.requireNonNull(month, "month");
222         DAY_OF_MONTH.checkValidValue(dayOfMonth);
223         if (dayOfMonth > month.maxLength()) {
224             throw new DateTimeException("Illegal value for DayOfMonth field, value " + dayOfMonth +
225                     " is not valid for month " + month.name());
226         }
227         return new MonthDay(month.getValue(), dayOfMonth);
228     }
229 
230     /**
231      * Obtains an instance of {@code MonthDay}.
232      * <p>
233      * The day-of-month must be valid for the month within a leap year.
234      * Hence, for month 2 (February), day 29 is valid.
235      * <p>
236      * For example, passing in month 4 (April) and day 31 will throw an exception, as
237      * there can never be April 31st in any year. By contrast, passing in
238      * February 29th is permitted, as that month-day can sometimes be valid.
239      *
240      * @param month  the month-of-year to represent, from 1 (January) to 12 (December)
241      * @param dayOfMonth  the day-of-month to represent, from 1 to 31
242      * @return the month-day, not null
243      * @throws DateTimeException if the value of any field is out of range,
244      *  or if the day-of-month is invalid for the month
245      */
246     public static MonthDay of(int month, int dayOfMonth) {
247         return of(Month.of(month), dayOfMonth);
248     }
249 
250     //-----------------------------------------------------------------------
251     /**
252      * Obtains an instance of {@code MonthDay} from a temporal object.
253      * <p>
254      * This obtains a month-day based on the specified temporal.
255      * A {@code TemporalAccessor} represents an arbitrary set of date and time information,
256      * which this factory converts to an instance of {@code MonthDay}.
257      * <p>
258      * The conversion extracts the {@link ChronoField#MONTH_OF_YEAR MONTH_OF_YEAR} and
259      * {@link ChronoField#DAY_OF_MONTH DAY_OF_MONTH} fields.
260      * The extraction is only permitted if the temporal object has an ISO
261      * chronology, or can be converted to a {@code LocalDate}.
262      * <p>
263      * This method matches the signature of the functional interface {@link TemporalQuery}
264      * allowing it to be used as a query via method reference, {@code MonthDay::from}.
265      *
266      * @param temporal  the temporal object to convert, not null
267      * @return the month-day, not null
268      * @throws DateTimeException if unable to convert to a {@code MonthDay}
269      */
270     public static MonthDay from(TemporalAccessor temporal) {
271         if (temporal instanceof MonthDay) {
272             return (MonthDay) temporal;
273         }
274         try {
275             if (IsoChronology.INSTANCE.equals(Chronology.from(temporal)) == false) {
276                 temporal = LocalDate.from(temporal);
277             }
278             return of(temporal.get(MONTH_OF_YEAR), temporal.get(DAY_OF_MONTH));
279         } catch (DateTimeException ex) {
280             throw new DateTimeException("Unable to obtain MonthDay from TemporalAccessor: " +
281                     temporal + " of type " + temporal.getClass().getName(), ex);
282         }
283     }
284 
285     //-----------------------------------------------------------------------
286     /**
287      * Obtains an instance of {@code MonthDay} from a text string such as {@code --12-03}.
288      * <p>
289      * The string must represent a valid month-day.
290      * The format is {@code --MM-dd}.
291      *
292      * @param text  the text to parse such as "--12-03", not null
293      * @return the parsed month-day, not null
294      * @throws DateTimeParseException if the text cannot be parsed
295      */
296     public static MonthDay parse(CharSequence text) {
297         return parse(text, PARSER);
298     }
299 
300     /**
301      * Obtains an instance of {@code MonthDay} from a text string using a specific formatter.
302      * <p>
303      * The text is parsed using the formatter, returning a month-day.
304      *
305      * @param text  the text to parse, not null
306      * @param formatter  the formatter to use, not null
307      * @return the parsed month-day, not null
308      * @throws DateTimeParseException if the text cannot be parsed
309      */
310     public static MonthDay parse(CharSequence text, DateTimeFormatter formatter) {
311         Objects.requireNonNull(formatter, "formatter");
312         return formatter.parse(text, MonthDay::from);
313     }
314 
315     //-----------------------------------------------------------------------
316     /**
317      * Constructor, previously validated.
318      *
319      * @param month  the month-of-year to represent, validated from 1 to 12
320      * @param dayOfMonth  the day-of-month to represent, validated from 1 to 29-31
321      */
322     private MonthDay(int month, int dayOfMonth) {
323         this.month = month;
324         this.day = dayOfMonth;
325     }
326 
327     //-----------------------------------------------------------------------
328     /**
329      * Checks if the specified field is supported.
330      * <p>
331      * This checks if this month-day can be queried for the specified field.
332      * If false, then calling the {@link #range(TemporalField) range} and
333      * {@link #get(TemporalField) get} methods will throw an exception.
334      * <p>
335      * If the field is a {@link ChronoField} then the query is implemented here.
336      * The supported fields are:
337      * <ul>
338      * <li>{@code MONTH_OF_YEAR}
339      * <li>{@code YEAR}
340      * </ul>
341      * All other {@code ChronoField} instances will return false.
342      * <p>
343      * If the field is not a {@code ChronoField}, then the result of this method
344      * is obtained by invoking {@code TemporalField.isSupportedBy(TemporalAccessor)}
345      * passing {@code this} as the argument.
346      * Whether the field is supported is determined by the field.
347      *
348      * @param field  the field to check, null returns false
349      * @return true if the field is supported on this month-day, false if not
350      */
351     @Override
352     public boolean isSupported(TemporalField field) {
353         if (field instanceof ChronoField) {
354             return field == MONTH_OF_YEAR || field == DAY_OF_MONTH;
355         }
356         return field != null && field.isSupportedBy(this);
357     }
358 
359     /**
360      * Gets the range of valid values for the specified field.
361      * <p>
362      * The range object expresses the minimum and maximum valid values for a field.
363      * This month-day is used to enhance the accuracy of the returned range.
364      * If it is not possible to return the range, because the field is not supported
365      * or for some other reason, an exception is thrown.
366      * <p>
367      * If the field is a {@link ChronoField} then the query is implemented here.
368      * The {@link #isSupported(TemporalField) supported fields} will return
369      * appropriate range instances.
370      * All other {@code ChronoField} instances will throw an {@code UnsupportedTemporalTypeException}.
371      * <p>
372      * If the field is not a {@code ChronoField}, then the result of this method
373      * is obtained by invoking {@code TemporalField.rangeRefinedBy(TemporalAccessor)}
374      * passing {@code this} as the argument.
375      * Whether the range can be obtained is determined by the field.
376      *
377      * @param field  the field to query the range for, not null
378      * @return the range of valid values for the field, not null
379      * @throws DateTimeException if the range for the field cannot be obtained
380      * @throws UnsupportedTemporalTypeException if the field is not supported
381      */
382     @Override
383     public ValueRange range(TemporalField field) {
384         if (field == MONTH_OF_YEAR) {
385             return field.range();
386         } else if (field == DAY_OF_MONTH) {
387             return ValueRange.of(1, getMonth().minLength(), getMonth().maxLength());
388         }
389         return TemporalAccessor.super.range(field);
390     }
391 
392     /**
393      * Gets the value of the specified field from this month-day as an {@code int}.
394      * <p>
395      * This queries this month-day for the value of the specified field.
396      * The returned value will always be within the valid range of values for the field.
397      * If it is not possible to return the value, because the field is not supported
398      * or for some other reason, an exception is thrown.
399      * <p>
400      * If the field is a {@link ChronoField} then the query is implemented here.
401      * The {@link #isSupported(TemporalField) supported fields} will return valid
402      * values based on this month-day.
403      * All other {@code ChronoField} instances will throw an {@code UnsupportedTemporalTypeException}.
404      * <p>
405      * If the field is not a {@code ChronoField}, then the result of this method
406      * is obtained by invoking {@code TemporalField.getFrom(TemporalAccessor)}
407      * passing {@code this} as the argument. Whether the value can be obtained,
408      * and what the value represents, is determined by the field.
409      *
410      * @param field  the field to get, not null
411      * @return the value for the field
412      * @throws DateTimeException if a value for the field cannot be obtained or
413      *         the value is outside the range of valid values for the field
414      * @throws UnsupportedTemporalTypeException if the field is not supported or
415      *         the range of values exceeds an {@code int}
416      * @throws ArithmeticException if numeric overflow occurs
417      */
418     @Override  // override for Javadoc
419     public int get(TemporalField field) {
420         return range(field).checkValidIntValue(getLong(field), field);
421     }
422 
423     /**
424      * Gets the value of the specified field from this month-day as a {@code long}.
425      * <p>
426      * This queries this month-day for the value of the specified field.
427      * If it is not possible to return the value, because the field is not supported
428      * or for some other reason, an exception is thrown.
429      * <p>
430      * If the field is a {@link ChronoField} then the query is implemented here.
431      * The {@link #isSupported(TemporalField) supported fields} will return valid
432      * values based on this month-day.
433      * All other {@code ChronoField} instances will throw an {@code UnsupportedTemporalTypeException}.
434      * <p>
435      * If the field is not a {@code ChronoField}, then the result of this method
436      * is obtained by invoking {@code TemporalField.getFrom(TemporalAccessor)}
437      * passing {@code this} as the argument. Whether the value can be obtained,
438      * and what the value represents, is determined by the field.
439      *
440      * @param field  the field to get, not null
441      * @return the value for the field
442      * @throws DateTimeException if a value for the field cannot be obtained
443      * @throws UnsupportedTemporalTypeException if the field is not supported
444      * @throws ArithmeticException if numeric overflow occurs
445      */
446     @Override
447     public long getLong(TemporalField field) {
448         if (field instanceof ChronoField chronoField) {
449             return switch (chronoField) {
450                 // alignedDOW and alignedWOM not supported because they cannot be set in with()
451                 case DAY_OF_MONTH -> day;
452                 case MONTH_OF_YEAR -> month;
453                 default -> throw new UnsupportedTemporalTypeException("Unsupported field: " + field);
454             };
455         }
456         return field.getFrom(this);
457     }
458 
459     //-----------------------------------------------------------------------
460     /**
461      * Gets the month-of-year field from 1 to 12.
462      * <p>
463      * This method returns the month as an {@code int} from 1 to 12.
464      * Application code is frequently clearer if the enum {@link Month}
465      * is used by calling {@link #getMonth()}.
466      *
467      * @return the month-of-year, from 1 to 12
468      * @see #getMonth()
469      */
470     public int getMonthValue() {
471         return month;
472     }
473 
474     /**
475      * Gets the month-of-year field using the {@code Month} enum.
476      * <p>
477      * This method returns the enum {@link Month} for the month.
478      * This avoids confusion as to what {@code int} values mean.
479      * If you need access to the primitive {@code int} value then the enum
480      * provides the {@link Month#getValue() int value}.
481      *
482      * @return the month-of-year, not null
483      * @see #getMonthValue()
484      */
485     public Month getMonth() {
486         return Month.of(month);
487     }
488 
489     /**
490      * Gets the day-of-month field.
491      * <p>
492      * This method returns the primitive {@code int} value for the day-of-month.
493      *
494      * @return the day-of-month, from 1 to 31
495      */
496     public int getDayOfMonth() {
497         return day;
498     }
499 
500     //-----------------------------------------------------------------------
501     /**
502      * Checks if the year is valid for this month-day.
503      * <p>
504      * This method checks whether this month and day and the input year form
505      * a valid date. This can only return false for February 29th.
506      *
507      * @param year  the year to validate
508      * @return true if the year is valid for this month-day
509      * @see Year#isValidMonthDay(MonthDay)
510      */
511     public boolean isValidYear(int year) {
512         return (day == 29 && month == 2 && Year.isLeap(year) == false) == false;
513     }
514 
515     //-----------------------------------------------------------------------
516     /**
517      * Returns a copy of this {@code MonthDay} with the month-of-year altered.
518      * <p>
519      * This returns a month-day with the specified month.
520      * If the day-of-month is invalid for the specified month, the day will
521      * be adjusted to the last valid day-of-month.
522      * <p>
523      * This instance is immutable and unaffected by this method call.
524      *
525      * @param month  the month-of-year to set in the returned month-day, from 1 (January) to 12 (December)
526      * @return a {@code MonthDay} based on this month-day with the requested month, not null
527      * @throws DateTimeException if the month-of-year value is invalid
528      */
529     public MonthDay withMonth(int month) {
530         return with(Month.of(month));
531     }
532 
533     /**
534      * Returns a copy of this {@code MonthDay} with the month-of-year altered.
535      * <p>
536      * This returns a month-day with the specified month.
537      * If the day-of-month is invalid for the specified month, the day will
538      * be adjusted to the last valid day-of-month.
539      * <p>
540      * This instance is immutable and unaffected by this method call.
541      *
542      * @param month  the month-of-year to set in the returned month-day, not null
543      * @return a {@code MonthDay} based on this month-day with the requested month, not null
544      */
545     public MonthDay with(Month month) {
546         Objects.requireNonNull(month, "month");
547         if (month.getValue() == this.month) {
548             return this;
549         }
550         int day = Math.min(this.day, month.maxLength());
551         return new MonthDay(month.getValue(), day);
552     }
553 
554     /**
555      * Returns a copy of this {@code MonthDay} with the day-of-month altered.
556      * <p>
557      * This returns a month-day with the specified day-of-month.
558      * If the day-of-month is invalid for the month, an exception is thrown.
559      * <p>
560      * This instance is immutable and unaffected by this method call.
561      *
562      * @param dayOfMonth  the day-of-month to set in the return month-day, from 1 to 31
563      * @return a {@code MonthDay} based on this month-day with the requested day, not null
564      * @throws DateTimeException if the day-of-month value is invalid,
565      *  or if the day-of-month is invalid for the month
566      */
567     public MonthDay withDayOfMonth(int dayOfMonth) {
568         if (dayOfMonth == this.day) {
569             return this;
570         }
571         return of(month, dayOfMonth);
572     }
573 
574     //-----------------------------------------------------------------------
575     /**
576      * Queries this month-day using the specified query.
577      * <p>
578      * This queries this month-day using the specified query strategy object.
579      * The {@code TemporalQuery} object defines the logic to be used to
580      * obtain the result. Read the documentation of the query to understand
581      * what the result of this method will be.
582      * <p>
583      * The result of this method is obtained by invoking the
584      * {@link TemporalQuery#queryFrom(TemporalAccessor)} method on the
585      * specified query passing {@code this} as the argument.
586      *
587      * @param <R> the type of the result
588      * @param query  the query to invoke, not null
589      * @return the query result, null may be returned (defined by the query)
590      * @throws DateTimeException if unable to query (defined by the query)
591      * @throws ArithmeticException if numeric overflow occurs (defined by the query)
592      */
593     @SuppressWarnings("unchecked")
594     @Override
595     public <R> R query(TemporalQuery<R> query) {
596         if (query == TemporalQueries.chronology()) {
597             return (R) IsoChronology.INSTANCE;
598         }
599         return TemporalAccessor.super.query(query);
600     }
601 
602     /**
603      * Adjusts the specified temporal object to have this month-day.
604      * <p>
605      * This returns a temporal object of the same observable type as the input
606      * with the month and day-of-month changed to be the same as this.
607      * <p>
608      * The adjustment is equivalent to using {@link Temporal#with(TemporalField, long)}
609      * twice, passing {@link ChronoField#MONTH_OF_YEAR} and
610      * {@link ChronoField#DAY_OF_MONTH} as the fields.
611      * If the specified temporal object does not use the ISO calendar system then
612      * a {@code DateTimeException} is thrown.
613      * <p>
614      * In most cases, it is clearer to reverse the calling pattern by using
615      * {@link Temporal#with(TemporalAdjuster)}:
616      * <pre>
617      *   // these two lines are equivalent, but the second approach is recommended
618      *   temporal = thisMonthDay.adjustInto(temporal);
619      *   temporal = temporal.with(thisMonthDay);
620      * </pre>
621      * <p>
622      * This instance is immutable and unaffected by this method call.
623      *
624      * @param temporal  the target object to be adjusted, not null
625      * @return the adjusted object, not null
626      * @throws DateTimeException if unable to make the adjustment
627      * @throws ArithmeticException if numeric overflow occurs
628      */
629     @Override
630     public Temporal adjustInto(Temporal temporal) {
631         if (Chronology.from(temporal).equals(IsoChronology.INSTANCE) == false) {
632             throw new DateTimeException("Adjustment only supported on ISO date-time");
633         }
634         temporal = temporal.with(MONTH_OF_YEAR, month);
635         return temporal.with(DAY_OF_MONTH, Math.min(temporal.range(DAY_OF_MONTH).getMaximum(), day));
636     }
637 
638     /**
639      * Formats this month-day using the specified formatter.
640      * <p>
641      * This month-day will be passed to the formatter to produce a string.
642      *
643      * @param formatter  the formatter to use, not null
644      * @return the formatted month-day string, not null
645      * @throws DateTimeException if an error occurs during printing
646      */
647     public String format(DateTimeFormatter formatter) {
648         Objects.requireNonNull(formatter, "formatter");
649         return formatter.format(this);
650     }
651 
652     //-----------------------------------------------------------------------
653     /**
654      * Combines this month-day with a year to create a {@code LocalDate}.
655      * <p>
656      * This returns a {@code LocalDate} formed from this month-day and the specified year.
657      * <p>
658      * A month-day of February 29th will be adjusted to February 28th in the resulting
659      * date if the year is not a leap year.
660      * <p>
661      * This instance is immutable and unaffected by this method call.
662      *
663      * @param year  the year to use, from MIN_YEAR to MAX_YEAR
664      * @return the local date formed from this month-day and the specified year, not null
665      * @throws DateTimeException if the year is outside the valid range of years
666      */
667     public LocalDate atYear(int year) {
668         return LocalDate.of(year, month, isValidYear(year) ? day : 28);
669     }
670 
671     //-----------------------------------------------------------------------
672     /**
673      * Compares this month-day to another month-day.
674      * <p>
675      * The comparison is based first on value of the month, then on the value of the day.
676      * It is "consistent with equals", as defined by {@link Comparable}.
677      *
678      * @param other  the other month-day to compare to, not null
679      * @return the comparator value, that is less than zero if this is before {@code other},
680      *          zero if they are equal, greater than zero if this is after {@code other}
681      * @see #isBefore
682      * @see #isAfter
683      */
684     @Override
685     public int compareTo(MonthDay other) {
686         int cmp = (month - other.month);
687         if (cmp == 0) {
688             cmp = (day - other.day);
689         }
690         return cmp;
691     }
692 
693     /**
694      * Checks if this month-day is after the specified month-day.
695      *
696      * @param other  the other month-day to compare to, not null
697      * @return true if this is after the specified month-day
698      */
699     public boolean isAfter(MonthDay other) {
700         return compareTo(other) > 0;
701     }
702 
703     /**
704      * Checks if this month-day is before the specified month-day.
705      *
706      * @param other  the other month-day to compare to, not null
707      * @return true if this point is before the specified month-day
708      */
709     public boolean isBefore(MonthDay other) {
710         return compareTo(other) < 0;
711     }
712 
713     //-----------------------------------------------------------------------
714     /**
715      * Checks if this month-day is equal to another month-day.
716      * <p>
717      * The comparison is based on the time-line position of the month-day within a year.
718      *
719      * @param obj  the object to check, null returns false
720      * @return true if this is equal to the other month-day
721      */
722     @Override
723     public boolean equals(Object obj) {
724         if (this == obj) {
725             return true;
726         }
727         return (obj instanceof MonthDay other)
728                 && month == other.month
729                 && day == other.day;
730     }
731 
732     /**
733      * A hash code for this month-day.
734      *
735      * @return a suitable hash code
736      */
737     @Override
738     public int hashCode() {
739         return (month << 6) + day;
740     }
741 
742     //-----------------------------------------------------------------------
743     /**
744      * Outputs this month-day as a {@code String}, such as {@code --12-03}.
745      * <p>
746      * The output will be in the format {@code --MM-dd}:
747      *
748      * @return a string representation of this month-day, not null
749      */
750     @Override
751     public String toString() {
752         return new StringBuilder(10).append("--")
753             .append(month < 10 ? "0" : "").append(month)
754             .append(day < 10 ? "-0" : "-").append(day)
755             .toString();
756     }
757 
758     //-----------------------------------------------------------------------
759     /**
760      * Writes the object using a
761      * <a href="{@docRoot}/serialized-form.html#java.time.Ser">dedicated serialized form</a>.
762      * @serialData
763      * <pre>
764      *  out.writeByte(13);  // identifies a MonthDay
765      *  out.writeByte(month);
766      *  out.writeByte(day);
767      * </pre>
768      *
769      * @return the instance of {@code Ser}, not null
770      */
771     @java.io.Serial
772     private Object writeReplace() {
773         return new Ser(Ser.MONTH_DAY_TYPE, this);
774     }
775 
776     /**
777      * Defend against malicious streams.
778      *
779      * @param s the stream to read
780      * @throws InvalidObjectException always
781      */
782     @java.io.Serial
783     private void readObject(ObjectInputStream s) throws InvalidObjectException {
784         throw new InvalidObjectException("Deserialization via serialization delegate");
785     }
786 
787     void writeExternal(DataOutput out) throws IOException {
788         out.writeByte(month);
789         out.writeByte(day);
790     }
791 
792     static MonthDay readExternal(DataInput in) throws IOException {
793         byte month = in.readByte();
794         byte day = in.readByte();
795         return MonthDay.of(month, day);
796     }
797 
798 }