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