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.ERA;
  65 import static java.time.temporal.ChronoField.MONTH_OF_YEAR;
  66 import static java.time.temporal.ChronoField.PROLEPTIC_MONTH;
  67 import static java.time.temporal.ChronoField.YEAR;
  68 import static java.time.temporal.ChronoField.YEAR_OF_ERA;
  69 import static java.time.temporal.ChronoUnit.CENTURIES;
  70 import static java.time.temporal.ChronoUnit.DECADES;
  71 import static java.time.temporal.ChronoUnit.ERAS;
  72 import static java.time.temporal.ChronoUnit.MILLENNIA;
  73 import static java.time.temporal.ChronoUnit.MONTHS;
  74 import static java.time.temporal.ChronoUnit.YEARS;
  75 
  76 import java.io.DataInput;
  77 import java.io.DataOutput;
  78 import java.io.IOException;
  79 import java.io.InvalidObjectException;
  80 import java.io.ObjectInputStream;
  81 import java.io.ObjectStreamField;
  82 import java.io.Serial;
  83 import java.io.Serializable;
  84 import java.time.chrono.Chronology;
  85 import java.time.chrono.IsoChronology;
  86 import java.time.format.DateTimeFormatter;
  87 import java.time.format.DateTimeFormatterBuilder;
  88 import java.time.format.DateTimeParseException;
  89 import java.time.format.SignStyle;
  90 import java.time.temporal.ChronoField;
  91 import java.time.temporal.ChronoUnit;
  92 import java.time.temporal.Temporal;
  93 import java.time.temporal.TemporalAccessor;
  94 import java.time.temporal.TemporalAdjuster;
  95 import java.time.temporal.TemporalAmount;
  96 import java.time.temporal.TemporalField;
  97 import java.time.temporal.TemporalQueries;
  98 import java.time.temporal.TemporalQuery;
  99 import java.time.temporal.TemporalUnit;
 100 import java.time.temporal.UnsupportedTemporalTypeException;
 101 import java.time.temporal.ValueRange;
 102 import java.util.Objects;
 103 
 104 import jdk.internal.util.DecimalDigits;
 105 
 106 /**
 107  * A year-month in the ISO-8601 calendar system, such as {@code 2007-12}.
 108  * <p>
 109  * {@code YearMonth} is an immutable date-time object that represents the combination
 110  * of a year and month. Any field that can be derived from a year and month, such as
 111  * quarter-of-year, can be obtained.
 112  * <p>
 113  * This class does not store or represent a day, time or time-zone.
 114  * For example, the value "October 2007" can be stored in a {@code YearMonth}.
 115  * <p>
 116  * The ISO-8601 calendar system is the modern civil calendar system used today
 117  * in most of the world. It is equivalent to the proleptic Gregorian calendar
 118  * system, in which today's rules for leap years are applied for all time.
 119  * For most applications written today, the ISO-8601 rules are entirely suitable.
 120  * However, any application that makes use of historical dates, and requires them
 121  * to be accurate will find the ISO-8601 approach unsuitable.
 122  * <p>
 123  * This is a <a href="{@docRoot}/java.base/java/lang/doc-files/ValueBased.html">value-based</a>
 124  * class; programmers should treat instances that are
 125  * {@linkplain #equals(Object) equal} as interchangeable and should not
 126  * use instances for synchronization, or unpredictable behavior may
 127  * occur. For example, in a future release, synchronization may fail.
 128  * The {@code equals} method should be used for comparisons.
 129  *
 130  * @implSpec
 131  * This class is immutable and thread-safe.
 132  *
 133  * @since 1.8
 134  */
 135 @jdk.internal.ValueBased
 136 public final class YearMonth
 137         implements Temporal, TemporalAdjuster, Comparable<YearMonth>, Serializable {
 138 
 139     /**
 140      * Serialization version.
 141      */
 142     @java.io.Serial
 143     private static final long serialVersionUID = 4183400860270640070L;
 144 
 145     /**
 146      * For backward compatibility of the serialized {@code YearMonth.class} object,
 147      * explicitly declare the types of the serialized fields as defined in Java SE 8.
 148      * Instances of {@code YearMonth} are serialized using the dedicated
 149      * serialized form by {@code writeReplace}.
 150      * @serialField year int The year.
 151      * @serialField month int The month-of-year.
 152      */
 153     @java.io.Serial
 154     private static final ObjectStreamField[] serialPersistentFields = {
 155             new ObjectStreamField("year", int.class),
 156             new ObjectStreamField("month", int.class),
 157     };
 158     /**
 159      * Parser.
 160      */
 161     private static final DateTimeFormatter PARSER = new DateTimeFormatterBuilder()
 162         .appendValue(YEAR, 4, 10, SignStyle.EXCEEDS_PAD)
 163         .appendLiteral('-')
 164         .appendValue(MONTH_OF_YEAR, 2)
 165         .toFormatter();
 166 
 167     /**
 168      * @serial The year.
 169      */
 170     private final transient int year;
 171     /**
 172      * @serial The month-of-year..
 173      */
 174     private final transient byte month;
 175 
 176     //-----------------------------------------------------------------------
 177     /**
 178      * Obtains the current year-month from the system clock in the default time-zone.
 179      * <p>
 180      * This will query the {@link Clock#systemDefaultZone() system clock} in the default
 181      * time-zone to obtain the current year-month.
 182      * <p>
 183      * Using this method will prevent the ability to use an alternate clock for testing
 184      * because the clock is hard-coded.
 185      *
 186      * @return the current year-month using the system clock and default time-zone, not null
 187      */
 188     public static YearMonth now() {
 189         return now(Clock.systemDefaultZone());
 190     }
 191 
 192     /**
 193      * Obtains the current year-month from the system clock in the specified time-zone.
 194      * <p>
 195      * This will query the {@link Clock#system(ZoneId) system clock} to obtain the current year-month.
 196      * Specifying the time-zone avoids dependence on the default time-zone.
 197      * <p>
 198      * Using this method will prevent the ability to use an alternate clock for testing
 199      * because the clock is hard-coded.
 200      *
 201      * @param zone  the zone ID to use, not null
 202      * @return the current year-month using the system clock, not null
 203      */
 204     public static YearMonth now(ZoneId zone) {
 205         return now(Clock.system(zone));
 206     }
 207 
 208     /**
 209      * Obtains the current year-month from the specified clock.
 210      * <p>
 211      * This will query the specified clock to obtain the current year-month.
 212      * Using this method allows the use of an alternate clock for testing.
 213      * The alternate clock may be introduced using {@link Clock dependency injection}.
 214      *
 215      * @param clock  the clock to use, not null
 216      * @return the current year-month, not null
 217      */
 218     public static YearMonth now(Clock clock) {
 219         final LocalDate now = LocalDate.now(clock);  // called once
 220         return YearMonth.of(now.getYear(), now.getMonth());
 221     }
 222 
 223     //-----------------------------------------------------------------------
 224     /**
 225      * Obtains an instance of {@code YearMonth} from a year and month.
 226      *
 227      * @param year  the year to represent, from MIN_YEAR to MAX_YEAR
 228      * @param month  the month-of-year to represent, not null
 229      * @return the year-month, not null
 230      * @throws DateTimeException if the year value is invalid
 231      */
 232     public static YearMonth of(int year, Month month) {
 233         Objects.requireNonNull(month, "month");
 234         return of(year, month.getValue());
 235     }
 236 
 237     /**
 238      * Obtains an instance of {@code YearMonth} from a year and month.
 239      *
 240      * @param year  the year to represent, from MIN_YEAR to MAX_YEAR
 241      * @param month  the month-of-year to represent, from 1 (January) to 12 (December)
 242      * @return the year-month, not null
 243      * @throws DateTimeException if either field value is invalid
 244      */
 245     public static YearMonth of(int year, int month) {
 246         YEAR.checkValidValue(year);
 247         MONTH_OF_YEAR.checkValidValue(month);
 248         return new YearMonth(year, month);
 249     }
 250 
 251     //-----------------------------------------------------------------------
 252     /**
 253      * Obtains an instance of {@code YearMonth} from a temporal object.
 254      * <p>
 255      * This obtains a year-month based on the specified temporal.
 256      * A {@code TemporalAccessor} represents an arbitrary set of date and time information,
 257      * which this factory converts to an instance of {@code YearMonth}.
 258      * <p>
 259      * The conversion extracts the {@link ChronoField#YEAR YEAR} and
 260      * {@link ChronoField#MONTH_OF_YEAR MONTH_OF_YEAR} fields.
 261      * The extraction is only permitted if the temporal object has an ISO
 262      * chronology, or can be converted to a {@code LocalDate}.
 263      * <p>
 264      * This method matches the signature of the functional interface {@link TemporalQuery}
 265      * allowing it to be used as a query via method reference, {@code YearMonth::from}.
 266      *
 267      * @param temporal  the temporal object to convert, not null
 268      * @return the year-month, not null
 269      * @throws DateTimeException if unable to convert to a {@code YearMonth}
 270      */
 271     public static YearMonth from(TemporalAccessor temporal) {
 272         if (temporal instanceof YearMonth) {
 273             return (YearMonth) temporal;
 274         }
 275         Objects.requireNonNull(temporal, "temporal");
 276         try {
 277             if (IsoChronology.INSTANCE.equals(Chronology.from(temporal)) == false) {
 278                 temporal = LocalDate.from(temporal);
 279             }
 280             return of(temporal.get(YEAR), temporal.get(MONTH_OF_YEAR));
 281         } catch (DateTimeException ex) {
 282             throw new DateTimeException("Unable to obtain YearMonth from TemporalAccessor: " +
 283                     temporal + " of type " + temporal.getClass().getName(), ex);
 284         }
 285     }
 286 
 287     //-----------------------------------------------------------------------
 288     /**
 289      * Obtains an instance of {@code YearMonth} from a text string such as {@code 2007-12}.
 290      * <p>
 291      * The string must represent a valid year-month.
 292      * The format must be {@code uuuu-MM}.
 293      * Years outside the range 0000 to 9999 must be prefixed by the plus or minus symbol.
 294      *
 295      * @param text  the text to parse such as "2007-12", not null
 296      * @return the parsed year-month, not null
 297      * @throws DateTimeParseException if the text cannot be parsed
 298      */
 299     public static YearMonth parse(CharSequence text) {
 300         return parse(text, PARSER);
 301     }
 302 
 303     /**
 304      * Obtains an instance of {@code YearMonth} from a text string using a specific formatter.
 305      * <p>
 306      * The text is parsed using the formatter, returning a year-month.
 307      *
 308      * @param text  the text to parse, not null
 309      * @param formatter  the formatter to use, not null
 310      * @return the parsed year-month, not null
 311      * @throws DateTimeParseException if the text cannot be parsed
 312      */
 313     public static YearMonth parse(CharSequence text, DateTimeFormatter formatter) {
 314         Objects.requireNonNull(formatter, "formatter");
 315         return formatter.parse(text, YearMonth::from);
 316     }
 317 
 318     //-----------------------------------------------------------------------
 319     /**
 320      * Constructor.
 321      *
 322      * @param year  the year to represent, validated from MIN_YEAR to MAX_YEAR
 323      * @param month  the month-of-year to represent, validated from 1 (January) to 12 (December)
 324      */
 325     private YearMonth(int year, int month) {
 326         this.year = year;
 327         this.month = (byte) month;
 328     }
 329 
 330     /**
 331      * Returns a copy of this year-month with the new year and month, checking
 332      * to see if a new object is in fact required.
 333      *
 334      * @param newYear  the year to represent, validated from MIN_YEAR to MAX_YEAR
 335      * @param newMonth  the month-of-year to represent, validated not null
 336      * @return the year-month, not null
 337      */
 338     private YearMonth with(int newYear, int newMonth) {
 339         if (year == newYear && month == newMonth) {
 340             return this;
 341         }
 342         return new YearMonth(newYear, newMonth);
 343     }
 344 
 345     //-----------------------------------------------------------------------
 346     /**
 347      * Checks if the specified field is supported.
 348      * <p>
 349      * This checks if this year-month can be queried for the specified field.
 350      * If false, then calling the {@link #range(TemporalField) range},
 351      * {@link #get(TemporalField) get} and {@link #with(TemporalField, long)}
 352      * methods will throw an exception.
 353      * <p>
 354      * If the field is a {@link ChronoField} then the query is implemented here.
 355      * The supported fields are:
 356      * <ul>
 357      * <li>{@code MONTH_OF_YEAR}
 358      * <li>{@code PROLEPTIC_MONTH}
 359      * <li>{@code YEAR_OF_ERA}
 360      * <li>{@code YEAR}
 361      * <li>{@code ERA}
 362      * </ul>
 363      * All other {@code ChronoField} instances will return false.
 364      * <p>
 365      * If the field is not a {@code ChronoField}, then the result of this method
 366      * is obtained by invoking {@code TemporalField.isSupportedBy(TemporalAccessor)}
 367      * passing {@code this} as the argument.
 368      * Whether the field is supported is determined by the field.
 369      *
 370      * @param field  the field to check, null returns false
 371      * @return true if the field is supported on this year-month, false if not
 372      */
 373     @Override
 374     public boolean isSupported(TemporalField field) {
 375         if (field instanceof ChronoField) {
 376             return field == YEAR || field == MONTH_OF_YEAR ||
 377                     field == PROLEPTIC_MONTH || field == YEAR_OF_ERA || field == ERA;
 378         }
 379         return field != null && field.isSupportedBy(this);
 380     }
 381 
 382     /**
 383      * Checks if the specified unit is supported.
 384      * <p>
 385      * This checks if the specified unit can be added to, or subtracted from, this year-month.
 386      * If false, then calling the {@link #plus(long, TemporalUnit)} and
 387      * {@link #minus(long, TemporalUnit) minus} methods will throw an exception.
 388      * <p>
 389      * If the unit is a {@link ChronoUnit} then the query is implemented here.
 390      * The supported units are:
 391      * <ul>
 392      * <li>{@code MONTHS}
 393      * <li>{@code YEARS}
 394      * <li>{@code DECADES}
 395      * <li>{@code CENTURIES}
 396      * <li>{@code MILLENNIA}
 397      * <li>{@code ERAS}
 398      * </ul>
 399      * All other {@code ChronoUnit} instances will return false.
 400      * <p>
 401      * If the unit is not a {@code ChronoUnit}, then the result of this method
 402      * is obtained by invoking {@code TemporalUnit.isSupportedBy(Temporal)}
 403      * passing {@code this} as the argument.
 404      * Whether the unit is supported is determined by the unit.
 405      *
 406      * @param unit  the unit to check, null returns false
 407      * @return true if the unit can be added/subtracted, false if not
 408      */
 409     @Override
 410     public boolean isSupported(TemporalUnit unit) {
 411         if (unit instanceof ChronoUnit) {
 412             return unit == MONTHS || unit == YEARS || unit == DECADES || unit == CENTURIES || unit == MILLENNIA || unit == ERAS;
 413         }
 414         return unit != null && unit.isSupportedBy(this);
 415     }
 416 
 417     //-----------------------------------------------------------------------
 418     /**
 419      * Gets the range of valid values for the specified field.
 420      * <p>
 421      * The range object expresses the minimum and maximum valid values for a field.
 422      * This year-month is used to enhance the accuracy of the returned range.
 423      * If it is not possible to return the range, because the field is not supported
 424      * or for some other reason, an exception is thrown.
 425      * <p>
 426      * If the field is a {@link ChronoField} then the query is implemented here.
 427      * The {@link #isSupported(TemporalField) supported fields} will return
 428      * appropriate range instances.
 429      * All other {@code ChronoField} instances will throw an {@code UnsupportedTemporalTypeException}.
 430      * <p>
 431      * If the field is not a {@code ChronoField}, then the result of this method
 432      * is obtained by invoking {@code TemporalField.rangeRefinedBy(TemporalAccessor)}
 433      * passing {@code this} as the argument.
 434      * Whether the range can be obtained is determined by the field.
 435      *
 436      * @param field  the field to query the range for, not null
 437      * @return the range of valid values for the field, not null
 438      * @throws DateTimeException if the range for the field cannot be obtained
 439      * @throws UnsupportedTemporalTypeException if the field is not supported
 440      */
 441     @Override
 442     public ValueRange range(TemporalField field) {
 443         if (field == YEAR_OF_ERA) {
 444             return (getYear() <= 0 ? ValueRange.of(1, Year.MAX_VALUE + 1) : ValueRange.of(1, Year.MAX_VALUE));
 445         }
 446         return Temporal.super.range(field);
 447     }
 448 
 449     /**
 450      * Gets the value of the specified field from this year-month as an {@code int}.
 451      * <p>
 452      * This queries this year-month for the value of the specified field.
 453      * The returned value will always be within the valid range of values for the field.
 454      * If it is not possible to return the value, because the field is not supported
 455      * or for some other reason, an exception is thrown.
 456      * <p>
 457      * If the field is a {@link ChronoField} then the query is implemented here.
 458      * The {@link #isSupported(TemporalField) supported fields} will return valid
 459      * values based on this year-month, except {@code PROLEPTIC_MONTH} which is too
 460      * large to fit in an {@code int} and throw a {@code DateTimeException}.
 461      * All other {@code ChronoField} instances will throw an {@code UnsupportedTemporalTypeException}.
 462      * <p>
 463      * If the field is not a {@code ChronoField}, then the result of this method
 464      * is obtained by invoking {@code TemporalField.getFrom(TemporalAccessor)}
 465      * passing {@code this} as the argument. Whether the value can be obtained,
 466      * and what the value represents, is determined by the field.
 467      *
 468      * @param field  the field to get, not null
 469      * @return the value for the field
 470      * @throws DateTimeException if a value for the field cannot be obtained or
 471      *         the value is outside the range of valid values for the field
 472      * @throws UnsupportedTemporalTypeException if the field is not supported or
 473      *         the range of values exceeds an {@code int}
 474      * @throws ArithmeticException if numeric overflow occurs
 475      */
 476     @Override  // override for Javadoc
 477     public int get(TemporalField field) {
 478         return range(field).checkValidIntValue(getLong(field), field);
 479     }
 480 
 481     /**
 482      * Gets the value of the specified field from this year-month as a {@code long}.
 483      * <p>
 484      * This queries this year-month for the value of the specified field.
 485      * If it is not possible to return the value, because the field is not supported
 486      * or for some other reason, an exception is thrown.
 487      * <p>
 488      * If the field is a {@link ChronoField} then the query is implemented here.
 489      * The {@link #isSupported(TemporalField) supported fields} will return valid
 490      * values based on this year-month.
 491      * All other {@code ChronoField} instances will throw an {@code UnsupportedTemporalTypeException}.
 492      * <p>
 493      * If the field is not a {@code ChronoField}, then the result of this method
 494      * is obtained by invoking {@code TemporalField.getFrom(TemporalAccessor)}
 495      * passing {@code this} as the argument. Whether the value can be obtained,
 496      * and what the value represents, is determined by the field.
 497      *
 498      * @param field  the field to get, not null
 499      * @return the value for the field
 500      * @throws DateTimeException if a value for the field cannot be obtained
 501      * @throws UnsupportedTemporalTypeException if the field is not supported
 502      * @throws ArithmeticException if numeric overflow occurs
 503      */
 504     @Override
 505     public long getLong(TemporalField field) {
 506         if (field instanceof ChronoField chronoField) {
 507             return switch (chronoField) {
 508                 case MONTH_OF_YEAR   -> month;
 509                 case PROLEPTIC_MONTH -> getProlepticMonth();
 510                 case YEAR_OF_ERA     -> (year < 1 ? 1 - year : year);
 511                 case YEAR            -> year;
 512                 case ERA             -> (year < 1 ? 0 : 1);
 513                 default -> throw new UnsupportedTemporalTypeException("Unsupported field: " + field);
 514             };
 515         }
 516         return field.getFrom(this);
 517     }
 518 
 519     private long getProlepticMonth() {
 520         return (year * 12L + month - 1);
 521     }
 522 
 523     //-----------------------------------------------------------------------
 524     /**
 525      * Gets the year field.
 526      * <p>
 527      * This method returns the primitive {@code int} value for the year.
 528      * <p>
 529      * The year returned by this method is proleptic as per {@code get(YEAR)}.
 530      *
 531      * @return the year, from MIN_YEAR to MAX_YEAR
 532      */
 533     public int getYear() {
 534         return year;
 535     }
 536 
 537     /**
 538      * Gets the month-of-year field from 1 to 12.
 539      * <p>
 540      * This method returns the month as an {@code int} from 1 to 12.
 541      * Application code is frequently clearer if the enum {@link Month}
 542      * is used by calling {@link #getMonth()}.
 543      *
 544      * @return the month-of-year, from 1 to 12
 545      * @see #getMonth()
 546      */
 547     public int getMonthValue() {
 548         return month;
 549     }
 550 
 551     /**
 552      * Gets the month-of-year field using the {@code Month} enum.
 553      * <p>
 554      * This method returns the enum {@link Month} for the month.
 555      * This avoids confusion as to what {@code int} values mean.
 556      * If you need access to the primitive {@code int} value then the enum
 557      * provides the {@link Month#getValue() int value}.
 558      *
 559      * @return the month-of-year, not null
 560      * @see #getMonthValue()
 561      */
 562     public Month getMonth() {
 563         return Month.of(month);
 564     }
 565 
 566     //-----------------------------------------------------------------------
 567     /**
 568      * Checks if the year is a leap year, according to the ISO proleptic
 569      * calendar system rules.
 570      * <p>
 571      * This method applies the current rules for leap years across the whole time-line.
 572      * In general, a year is a leap year if it is divisible by four without
 573      * remainder. However, years divisible by 100, are not leap years, with
 574      * the exception of years divisible by 400 which are.
 575      * <p>
 576      * For example, 1904 is a leap year it is divisible by 4.
 577      * 1900 was not a leap year as it is divisible by 100, however 2000 was a
 578      * leap year as it is divisible by 400.
 579      * <p>
 580      * The calculation is proleptic - applying the same rules into the far future and far past.
 581      * This is historically inaccurate, but is correct for the ISO-8601 standard.
 582      *
 583      * @return true if the year is leap, false otherwise
 584      */
 585     public boolean isLeapYear() {
 586         return IsoChronology.INSTANCE.isLeapYear(year);
 587     }
 588 
 589     /**
 590      * Checks if the day-of-month is valid for this year-month.
 591      * <p>
 592      * This method checks whether this year and month and the input day form
 593      * a valid date.
 594      *
 595      * @param dayOfMonth  the day-of-month to validate, from 1 to 31, invalid value returns false
 596      * @return true if the day is valid for this year-month
 597      */
 598     public boolean isValidDay(int dayOfMonth) {
 599         return dayOfMonth >= 1 && dayOfMonth <= lengthOfMonth();
 600     }
 601 
 602     /**
 603      * Returns the length of the month, taking account of the year.
 604      * <p>
 605      * This returns the length of the month in days.
 606      * For example, a date in January would return 31.
 607      *
 608      * @return the length of the month in days, from 28 to 31
 609      */
 610     public int lengthOfMonth() {
 611         return getMonth().length(isLeapYear());
 612     }
 613 
 614     /**
 615      * Returns the length of the year.
 616      * <p>
 617      * This returns the length of the year in days, either 365 or 366.
 618      *
 619      * @return 366 if the year is leap, 365 otherwise
 620      */
 621     public int lengthOfYear() {
 622         return (isLeapYear() ? 366 : 365);
 623     }
 624 
 625     //-----------------------------------------------------------------------
 626     /**
 627      * Returns an adjusted copy of this year-month.
 628      * <p>
 629      * This returns a {@code YearMonth}, based on this one, with the year-month adjusted.
 630      * The adjustment takes place using the specified adjuster strategy object.
 631      * Read the documentation of the adjuster to understand what adjustment will be made.
 632      * <p>
 633      * A simple adjuster might simply set the one of the fields, such as the year field.
 634      * A more complex adjuster might set the year-month to the next month that
 635      * Halley's comet will pass the Earth.
 636      * <p>
 637      * The result of this method is obtained by invoking the
 638      * {@link TemporalAdjuster#adjustInto(Temporal)} method on the
 639      * specified adjuster passing {@code this} as the argument.
 640      * <p>
 641      * This instance is immutable and unaffected by this method call.
 642      *
 643      * @param adjuster the adjuster to use, not null
 644      * @return a {@code YearMonth} based on {@code this} with the adjustment made, not null
 645      * @throws DateTimeException if the adjustment cannot be made
 646      * @throws ArithmeticException if numeric overflow occurs
 647      */
 648     @Override
 649     public YearMonth with(TemporalAdjuster adjuster) {
 650         return (YearMonth) adjuster.adjustInto(this);
 651     }
 652 
 653     /**
 654      * Returns a copy of this year-month with the specified field set to a new value.
 655      * <p>
 656      * This returns a {@code YearMonth}, based on this one, with the value
 657      * for the specified field changed.
 658      * This can be used to change any supported field, such as the year or month.
 659      * If it is not possible to set the value, because the field is not supported or for
 660      * some other reason, an exception is thrown.
 661      * <p>
 662      * If the field is a {@link ChronoField} then the adjustment is implemented here.
 663      * The supported fields behave as follows:
 664      * <ul>
 665      * <li>{@code MONTH_OF_YEAR} -
 666      *  Returns a {@code YearMonth} with the specified month-of-year.
 667      *  The year will be unchanged.
 668      * <li>{@code PROLEPTIC_MONTH} -
 669      *  Returns a {@code YearMonth} with the specified proleptic-month.
 670      *  This completely replaces the year and month of this object.
 671      * <li>{@code YEAR_OF_ERA} -
 672      *  Returns a {@code YearMonth} with the specified year-of-era
 673      *  The month and era will be unchanged.
 674      * <li>{@code YEAR} -
 675      *  Returns a {@code YearMonth} with the specified year.
 676      *  The month will be unchanged.
 677      * <li>{@code ERA} -
 678      *  Returns a {@code YearMonth} with the specified era.
 679      *  The month and year-of-era will be unchanged.
 680      * </ul>
 681      * <p>
 682      * In all cases, if the new value is outside the valid range of values for the field
 683      * then a {@code DateTimeException} will be thrown.
 684      * <p>
 685      * All other {@code ChronoField} instances will throw an {@code UnsupportedTemporalTypeException}.
 686      * <p>
 687      * If the field is not a {@code ChronoField}, then the result of this method
 688      * is obtained by invoking {@code TemporalField.adjustInto(Temporal, long)}
 689      * passing {@code this} as the argument. In this case, the field determines
 690      * whether and how to adjust the instant.
 691      * <p>
 692      * This instance is immutable and unaffected by this method call.
 693      *
 694      * @param field  the field to set in the result, not null
 695      * @param newValue  the new value of the field in the result
 696      * @return a {@code YearMonth} based on {@code this} with the specified field set, not null
 697      * @throws DateTimeException if the field cannot be set
 698      * @throws UnsupportedTemporalTypeException if the field is not supported
 699      * @throws ArithmeticException if numeric overflow occurs
 700      */
 701     @Override
 702     public YearMonth with(TemporalField field, long newValue) {
 703         if (field instanceof ChronoField chronoField) {
 704             chronoField.checkValidValue(newValue);
 705             return switch (chronoField) {
 706                 case MONTH_OF_YEAR   -> withMonth((int) newValue);
 707                 case PROLEPTIC_MONTH -> plusMonths(newValue - getProlepticMonth());
 708                 case YEAR_OF_ERA     -> withYear((int) (year < 1 ? 1 - newValue : newValue));
 709                 case YEAR            -> withYear((int) newValue);
 710                 case ERA             -> (getLong(ERA) == newValue ? this : withYear(1 - year));
 711                 default -> throw new UnsupportedTemporalTypeException("Unsupported field: " + field);
 712             };
 713         }
 714         return field.adjustInto(this, newValue);
 715     }
 716 
 717     //-----------------------------------------------------------------------
 718     /**
 719      * Returns a copy of this {@code YearMonth} with the year altered.
 720      * <p>
 721      * This instance is immutable and unaffected by this method call.
 722      *
 723      * @param year  the year to set in the returned year-month, from MIN_YEAR to MAX_YEAR
 724      * @return a {@code YearMonth} based on this year-month with the requested year, not null
 725      * @throws DateTimeException if the year value is invalid
 726      */
 727     public YearMonth withYear(int year) {
 728         YEAR.checkValidValue(year);
 729         return with(year, month);
 730     }
 731 
 732     /**
 733      * Returns a copy of this {@code YearMonth} with the month-of-year altered.
 734      * <p>
 735      * This instance is immutable and unaffected by this method call.
 736      *
 737      * @param month  the month-of-year to set in the returned year-month, from 1 (January) to 12 (December)
 738      * @return a {@code YearMonth} based on this year-month with the requested month, not null
 739      * @throws DateTimeException if the month-of-year value is invalid
 740      */
 741     public YearMonth withMonth(int month) {
 742         MONTH_OF_YEAR.checkValidValue(month);
 743         return with(year, month);
 744     }
 745 
 746     //-----------------------------------------------------------------------
 747     /**
 748      * Returns a copy of this year-month with the specified amount added.
 749      * <p>
 750      * This returns a {@code YearMonth}, based on this one, with the specified amount added.
 751      * The amount is typically {@link Period} but may be any other type implementing
 752      * the {@link TemporalAmount} interface.
 753      * <p>
 754      * The calculation is delegated to the amount object by calling
 755      * {@link TemporalAmount#addTo(Temporal)}. The amount implementation is free
 756      * to implement the addition in any way it wishes, however it typically
 757      * calls back to {@link #plus(long, TemporalUnit)}. Consult the documentation
 758      * of the amount implementation to determine if it can be successfully added.
 759      * <p>
 760      * This instance is immutable and unaffected by this method call.
 761      *
 762      * @param amountToAdd  the amount to add, not null
 763      * @return a {@code YearMonth} based on this year-month with the addition made, not null
 764      * @throws DateTimeException if the addition cannot be made
 765      * @throws ArithmeticException if numeric overflow occurs
 766      */
 767     @Override
 768     public YearMonth plus(TemporalAmount amountToAdd) {
 769         return (YearMonth) amountToAdd.addTo(this);
 770     }
 771 
 772     /**
 773      * Returns a copy of this year-month with the specified amount added.
 774      * <p>
 775      * This returns a {@code YearMonth}, based on this one, with the amount
 776      * in terms of the unit added. If it is not possible to add the amount, because the
 777      * unit is not supported or for some other reason, an exception is thrown.
 778      * <p>
 779      * If the field is a {@link ChronoUnit} then the addition is implemented here.
 780      * The supported fields behave as follows:
 781      * <ul>
 782      * <li>{@code MONTHS} -
 783      *  Returns a {@code YearMonth} with the specified number of months added.
 784      *  This is equivalent to {@link #plusMonths(long)}.
 785      * <li>{@code YEARS} -
 786      *  Returns a {@code YearMonth} with the specified number of years added.
 787      *  This is equivalent to {@link #plusYears(long)}.
 788      * <li>{@code DECADES} -
 789      *  Returns a {@code YearMonth} with the specified number of decades added.
 790      *  This is equivalent to calling {@link #plusYears(long)} with the amount
 791      *  multiplied by 10.
 792      * <li>{@code CENTURIES} -
 793      *  Returns a {@code YearMonth} with the specified number of centuries added.
 794      *  This is equivalent to calling {@link #plusYears(long)} with the amount
 795      *  multiplied by 100.
 796      * <li>{@code MILLENNIA} -
 797      *  Returns a {@code YearMonth} with the specified number of millennia added.
 798      *  This is equivalent to calling {@link #plusYears(long)} with the amount
 799      *  multiplied by 1,000.
 800      * <li>{@code ERAS} -
 801      *  Returns a {@code YearMonth} with the specified number of eras added.
 802      *  Only two eras are supported so the amount must be one, zero or minus one.
 803      *  If the amount is non-zero then the year is changed such that the year-of-era
 804      *  is unchanged.
 805      * </ul>
 806      * <p>
 807      * All other {@code ChronoUnit} instances will throw an {@code UnsupportedTemporalTypeException}.
 808      * <p>
 809      * If the field is not a {@code ChronoUnit}, then the result of this method
 810      * is obtained by invoking {@code TemporalUnit.addTo(Temporal, long)}
 811      * passing {@code this} as the argument. In this case, the unit determines
 812      * whether and how to perform the addition.
 813      * <p>
 814      * This instance is immutable and unaffected by this method call.
 815      *
 816      * @param amountToAdd  the amount of the unit to add to the result, may be negative
 817      * @param unit  the unit of the amount to add, not null
 818      * @return a {@code YearMonth} based on this year-month with the specified amount added, not null
 819      * @throws DateTimeException if the addition cannot be made
 820      * @throws UnsupportedTemporalTypeException if the unit is not supported
 821      * @throws ArithmeticException if numeric overflow occurs
 822      */
 823     @Override
 824     public YearMonth plus(long amountToAdd, TemporalUnit unit) {
 825         if (unit instanceof ChronoUnit chronoUnit) {
 826             return switch (chronoUnit) {
 827                 case MONTHS    -> plusMonths(amountToAdd);
 828                 case YEARS     -> plusYears(amountToAdd);
 829                 case DECADES   -> plusYears(Math.multiplyExact(amountToAdd, 10));
 830                 case CENTURIES -> plusYears(Math.multiplyExact(amountToAdd, 100));
 831                 case MILLENNIA -> plusYears(Math.multiplyExact(amountToAdd, 1000));
 832                 case ERAS      -> with(ERA, Math.addExact(getLong(ERA), amountToAdd));
 833                 default -> throw new UnsupportedTemporalTypeException("Unsupported unit: " + unit);
 834             };
 835         }
 836         return unit.addTo(this, amountToAdd);
 837     }
 838 
 839     /**
 840      * Returns a copy of this {@code YearMonth} with the specified number of years added.
 841      * <p>
 842      * This instance is immutable and unaffected by this method call.
 843      *
 844      * @param yearsToAdd  the years to add, may be negative
 845      * @return a {@code YearMonth} based on this year-month with the years added, not null
 846      * @throws DateTimeException if the result exceeds the supported range
 847      */
 848     public YearMonth plusYears(long yearsToAdd) {
 849         if (yearsToAdd == 0) {
 850             return this;
 851         }
 852         int newYear = YEAR.checkValidIntValue(year + yearsToAdd);  // safe overflow
 853         return with(newYear, month);
 854     }
 855 
 856     /**
 857      * Returns a copy of this {@code YearMonth} with the specified number of months added.
 858      * <p>
 859      * This instance is immutable and unaffected by this method call.
 860      *
 861      * @param monthsToAdd  the months to add, may be negative
 862      * @return a {@code YearMonth} based on this year-month with the months added, not null
 863      * @throws DateTimeException if the result exceeds the supported range
 864      */
 865     public YearMonth plusMonths(long monthsToAdd) {
 866         if (monthsToAdd == 0) {
 867             return this;
 868         }
 869         long monthCount = year * 12L + (month - 1);
 870         long calcMonths = monthCount + monthsToAdd;  // safe overflow
 871         int newYear = YEAR.checkValidIntValue(Math.floorDiv(calcMonths, 12));
 872         int newMonth = Math.floorMod(calcMonths, 12) + 1;
 873         return with(newYear, newMonth);
 874     }
 875 
 876     //-----------------------------------------------------------------------
 877     /**
 878      * Returns a copy of this year-month with the specified amount subtracted.
 879      * <p>
 880      * This returns a {@code YearMonth}, based on this one, with the specified amount subtracted.
 881      * The amount is typically {@link Period} but may be any other type implementing
 882      * the {@link TemporalAmount} interface.
 883      * <p>
 884      * The calculation is delegated to the amount object by calling
 885      * {@link TemporalAmount#subtractFrom(Temporal)}. The amount implementation is free
 886      * to implement the subtraction in any way it wishes, however it typically
 887      * calls back to {@link #minus(long, TemporalUnit)}. Consult the documentation
 888      * of the amount implementation to determine if it can be successfully subtracted.
 889      * <p>
 890      * This instance is immutable and unaffected by this method call.
 891      *
 892      * @param amountToSubtract  the amount to subtract, not null
 893      * @return a {@code YearMonth} based on this year-month with the subtraction made, not null
 894      * @throws DateTimeException if the subtraction cannot be made
 895      * @throws ArithmeticException if numeric overflow occurs
 896      */
 897     @Override
 898     public YearMonth minus(TemporalAmount amountToSubtract) {
 899         return (YearMonth) amountToSubtract.subtractFrom(this);
 900     }
 901 
 902     /**
 903      * Returns a copy of this year-month with the specified amount subtracted.
 904      * <p>
 905      * This returns a {@code YearMonth}, based on this one, with the amount
 906      * in terms of the unit subtracted. If it is not possible to subtract the amount,
 907      * because the unit is not supported or for some other reason, an exception is thrown.
 908      * <p>
 909      * This method is equivalent to {@link #plus(long, TemporalUnit)} with the amount negated.
 910      * See that method for a full description of how addition, and thus subtraction, works.
 911      * <p>
 912      * This instance is immutable and unaffected by this method call.
 913      *
 914      * @param amountToSubtract  the amount of the unit to subtract from the result, may be negative
 915      * @param unit  the unit of the amount to subtract, not null
 916      * @return a {@code YearMonth} based on this year-month with the specified amount subtracted, not null
 917      * @throws DateTimeException if the subtraction cannot be made
 918      * @throws UnsupportedTemporalTypeException if the unit is not supported
 919      * @throws ArithmeticException if numeric overflow occurs
 920      */
 921     @Override
 922     public YearMonth minus(long amountToSubtract, TemporalUnit unit) {
 923         return (amountToSubtract == Long.MIN_VALUE ? plus(Long.MAX_VALUE, unit).plus(1, unit) : plus(-amountToSubtract, unit));
 924     }
 925 
 926     /**
 927      * Returns a copy of this {@code YearMonth} with the specified number of years subtracted.
 928      * <p>
 929      * This instance is immutable and unaffected by this method call.
 930      *
 931      * @param yearsToSubtract  the years to subtract, may be negative
 932      * @return a {@code YearMonth} based on this year-month with the years subtracted, not null
 933      * @throws DateTimeException if the result exceeds the supported range
 934      */
 935     public YearMonth minusYears(long yearsToSubtract) {
 936         return (yearsToSubtract == Long.MIN_VALUE ? plusYears(Long.MAX_VALUE).plusYears(1) : plusYears(-yearsToSubtract));
 937     }
 938 
 939     /**
 940      * Returns a copy of this {@code YearMonth} with the specified number of months subtracted.
 941      * <p>
 942      * This instance is immutable and unaffected by this method call.
 943      *
 944      * @param monthsToSubtract  the months to subtract, may be negative
 945      * @return a {@code YearMonth} based on this year-month with the months subtracted, not null
 946      * @throws DateTimeException if the result exceeds the supported range
 947      */
 948     public YearMonth minusMonths(long monthsToSubtract) {
 949         return (monthsToSubtract == Long.MIN_VALUE ? plusMonths(Long.MAX_VALUE).plusMonths(1) : plusMonths(-monthsToSubtract));
 950     }
 951 
 952     //-----------------------------------------------------------------------
 953     /**
 954      * Queries this year-month using the specified query.
 955      * <p>
 956      * This queries this year-month using the specified query strategy object.
 957      * The {@code TemporalQuery} object defines the logic to be used to
 958      * obtain the result. Read the documentation of the query to understand
 959      * what the result of this method will be.
 960      * <p>
 961      * The result of this method is obtained by invoking the
 962      * {@link TemporalQuery#queryFrom(TemporalAccessor)} method on the
 963      * specified query passing {@code this} as the argument.
 964      *
 965      * @param <R> the type of the result
 966      * @param query  the query to invoke, not null
 967      * @return the query result, null may be returned (defined by the query)
 968      * @throws DateTimeException if unable to query (defined by the query)
 969      * @throws ArithmeticException if numeric overflow occurs (defined by the query)
 970      */
 971     @SuppressWarnings("unchecked")
 972     @Override
 973     public <R> R query(TemporalQuery<R> query) {
 974         if (query == TemporalQueries.chronology()) {
 975             return (R) IsoChronology.INSTANCE;
 976         } else if (query == TemporalQueries.precision()) {
 977             return (R) MONTHS;
 978         }
 979         return Temporal.super.query(query);
 980     }
 981 
 982     /**
 983      * Adjusts the specified temporal object to have this year-month.
 984      * <p>
 985      * This returns a temporal object of the same observable type as the input
 986      * with the year and month changed to be the same as this.
 987      * <p>
 988      * The adjustment is equivalent to using {@link Temporal#with(TemporalField, long)}
 989      * passing {@link ChronoField#PROLEPTIC_MONTH} as the field.
 990      * If the specified temporal object does not use the ISO calendar system then
 991      * a {@code DateTimeException} is thrown.
 992      * <p>
 993      * In most cases, it is clearer to reverse the calling pattern by using
 994      * {@link Temporal#with(TemporalAdjuster)}:
 995      * <pre>
 996      *   // these two lines are equivalent, but the second approach is recommended
 997      *   temporal = thisYearMonth.adjustInto(temporal);
 998      *   temporal = temporal.with(thisYearMonth);
 999      * </pre>
1000      * <p>
1001      * This instance is immutable and unaffected by this method call.
1002      *
1003      * @param temporal  the target object to be adjusted, not null
1004      * @return the adjusted object, not null
1005      * @throws DateTimeException if unable to make the adjustment
1006      * @throws ArithmeticException if numeric overflow occurs
1007      */
1008     @Override
1009     public Temporal adjustInto(Temporal temporal) {
1010         if (Chronology.from(temporal).equals(IsoChronology.INSTANCE) == false) {
1011             throw new DateTimeException("Adjustment only supported on ISO date-time");
1012         }
1013         return temporal.with(PROLEPTIC_MONTH, getProlepticMonth());
1014     }
1015 
1016     /**
1017      * Calculates the amount of time until another year-month in terms of the specified unit.
1018      * <p>
1019      * This calculates the amount of time between two {@code YearMonth}
1020      * objects in terms of a single {@code TemporalUnit}.
1021      * The start and end points are {@code this} and the specified year-month.
1022      * The result will be negative if the end is before the start.
1023      * The {@code Temporal} passed to this method is converted to a
1024      * {@code YearMonth} using {@link #from(TemporalAccessor)}.
1025      * For example, the amount in years between two year-months can be calculated
1026      * using {@code startYearMonth.until(endYearMonth, YEARS)}.
1027      * <p>
1028      * The calculation returns a whole number, representing the number of
1029      * complete units between the two year-months.
1030      * For example, the amount in decades between 2012-06 and 2032-05
1031      * will only be one decade as it is one month short of two decades.
1032      * <p>
1033      * There are two equivalent ways of using this method.
1034      * The first is to invoke this method.
1035      * The second is to use {@link TemporalUnit#between(Temporal, Temporal)}:
1036      * <pre>
1037      *   // these two lines are equivalent
1038      *   amount = start.until(end, MONTHS);
1039      *   amount = MONTHS.between(start, end);
1040      * </pre>
1041      * The choice should be made based on which makes the code more readable.
1042      * <p>
1043      * The calculation is implemented in this method for {@link ChronoUnit}.
1044      * The units {@code MONTHS}, {@code YEARS}, {@code DECADES},
1045      * {@code CENTURIES}, {@code MILLENNIA} and {@code ERAS} are supported.
1046      * Other {@code ChronoUnit} values will throw an exception.
1047      * <p>
1048      * If the unit is not a {@code ChronoUnit}, then the result of this method
1049      * is obtained by invoking {@code TemporalUnit.between(Temporal, Temporal)}
1050      * passing {@code this} as the first argument and the converted input temporal
1051      * as the second argument.
1052      * <p>
1053      * This instance is immutable and unaffected by this method call.
1054      *
1055      * @param endExclusive  the end date, exclusive, which is converted to a {@code YearMonth}, not null
1056      * @param unit  the unit to measure the amount in, not null
1057      * @return the amount of time between this year-month and the end year-month
1058      * @throws DateTimeException if the amount cannot be calculated, or the end
1059      *  temporal cannot be converted to a {@code YearMonth}
1060      * @throws UnsupportedTemporalTypeException if the unit is not supported
1061      * @throws ArithmeticException if numeric overflow occurs
1062      */
1063     @Override
1064     public long until(Temporal endExclusive, TemporalUnit unit) {
1065         YearMonth end = YearMonth.from(endExclusive);
1066         if (unit instanceof ChronoUnit chronoUnit) {
1067             long monthsUntil = end.getProlepticMonth() - getProlepticMonth();  // no overflow
1068             return switch (chronoUnit) {
1069                 case MONTHS    -> monthsUntil;
1070                 case YEARS     -> monthsUntil / 12;
1071                 case DECADES   -> monthsUntil / 120;
1072                 case CENTURIES -> monthsUntil / 1200;
1073                 case MILLENNIA -> monthsUntil / 12000;
1074                 case ERAS      -> end.getLong(ERA) - getLong(ERA);
1075                 default -> throw new UnsupportedTemporalTypeException("Unsupported unit: " + unit);
1076             };
1077         }
1078         return unit.between(this, end);
1079     }
1080 
1081     /**
1082      * Formats this year-month using the specified formatter.
1083      * <p>
1084      * This year-month will be passed to the formatter to produce a string.
1085      *
1086      * @param formatter  the formatter to use, not null
1087      * @return the formatted year-month string, not null
1088      * @throws DateTimeException if an error occurs during printing
1089      */
1090     public String format(DateTimeFormatter formatter) {
1091         Objects.requireNonNull(formatter, "formatter");
1092         return formatter.format(this);
1093     }
1094 
1095     //-----------------------------------------------------------------------
1096     /**
1097      * Combines this year-month with a day-of-month to create a {@code LocalDate}.
1098      * <p>
1099      * This returns a {@code LocalDate} formed from this year-month and the specified day-of-month.
1100      * <p>
1101      * The day-of-month value must be valid for the year-month.
1102      * <p>
1103      * This method can be used as part of a chain to produce a date:
1104      * <pre>
1105      *  LocalDate date = year.atMonth(month).atDay(day);
1106      * </pre>
1107      *
1108      * @param dayOfMonth  the day-of-month to use, from 1 to 31
1109      * @return the date formed from this year-month and the specified day, not null
1110      * @throws DateTimeException if the day is invalid for the year-month
1111      * @see #isValidDay(int)
1112      */
1113     public LocalDate atDay(int dayOfMonth) {
1114         return LocalDate.of(year, month, dayOfMonth);
1115     }
1116 
1117     /**
1118      * Returns a {@code LocalDate} at the end of the month.
1119      * <p>
1120      * This returns a {@code LocalDate} based on this year-month.
1121      * The day-of-month is set to the last valid day of the month, taking
1122      * into account leap years.
1123      * <p>
1124      * This method can be used as part of a chain to produce a date:
1125      * <pre>
1126      *  LocalDate date = year.atMonth(month).atEndOfMonth();
1127      * </pre>
1128      *
1129      * @return the last valid date of this year-month, not null
1130      */
1131     public LocalDate atEndOfMonth() {
1132         return LocalDate.of(year, month, lengthOfMonth());
1133     }
1134 
1135     //-----------------------------------------------------------------------
1136     /**
1137      * Compares this year-month to another year-month.
1138      * <p>
1139      * The comparison is based first on the value of the year, then on the value of the month.
1140      * It is "consistent with equals", as defined by {@link Comparable}.
1141      *
1142      * @param other  the other year-month to compare to, not null
1143      * @return the comparator value, that is less than zero if this is before {@code other},
1144      *          zero if they are equal, greater than zero if this is after {@code other}
1145      * @see #isBefore
1146      * @see #isAfter
1147      */
1148     @Override
1149     public int compareTo(YearMonth other) {
1150         int cmp = (year - other.year);
1151         if (cmp == 0) {
1152             cmp = (month - other.month);
1153         }
1154         return cmp;
1155     }
1156 
1157     /**
1158      * Checks if this year-month is after the specified year-month.
1159      *
1160      * @param other  the other year-month to compare to, not null
1161      * @return true if this is after the specified year-month
1162      */
1163     public boolean isAfter(YearMonth other) {
1164         return compareTo(other) > 0;
1165     }
1166 
1167     /**
1168      * Checks if this year-month is before the specified year-month.
1169      *
1170      * @param other  the other year-month to compare to, not null
1171      * @return true if this point is before the specified year-month
1172      */
1173     public boolean isBefore(YearMonth other) {
1174         return compareTo(other) < 0;
1175     }
1176 
1177     //-----------------------------------------------------------------------
1178     /**
1179      * Checks if this year-month is equal to another year-month.
1180      * <p>
1181      * The comparison is based on the time-line position of the year-months.
1182      *
1183      * @param obj  the object to check, null returns false
1184      * @return true if this is equal to the other year-month
1185      */
1186     @Override
1187     public boolean equals(Object obj) {
1188         if (this == obj) {
1189             return true;
1190         }
1191         return (obj instanceof YearMonth other)
1192                 && year == other.year
1193                 && month == other.month;
1194     }
1195 
1196     /**
1197      * A hash code for this year-month.
1198      *
1199      * @return a suitable hash code
1200      */
1201     @Override
1202     public int hashCode() {
1203         return year ^ (month << 27);
1204     }
1205 
1206     //-----------------------------------------------------------------------
1207     /**
1208      * Outputs this year-month as a {@code String}, such as {@code 2007-12}.
1209      * <p>
1210      * The output will be in the format {@code uuuu-MM}:
1211      *
1212      * @return a string representation of this year-month, not null
1213      */
1214     @Override
1215     public String toString() {
1216         int absYear = Math.abs(year);
1217         StringBuilder buf = new StringBuilder(9);
1218         if (absYear < 10000) {
1219             if (year < 0) {
1220                 buf.append('-');
1221             }
1222             DecimalDigits.appendQuad(buf, absYear);
1223         } else {
1224             buf.append(year);
1225         }
1226         buf.append('-');
1227         DecimalDigits.appendPair(buf, month);
1228         return buf.toString();
1229     }
1230 
1231     //-----------------------------------------------------------------------
1232     /**
1233      * Writes the object using a
1234      * <a href="{@docRoot}/serialized-form.html#java.time.Ser">dedicated serialized form</a>.
1235      * @serialData
1236      * <pre>
1237      *  out.writeByte(12);  // identifies a YearMonth
1238      *  out.writeInt(year);
1239      *  out.writeByte(month);
1240      * </pre>
1241      *
1242      * @return the instance of {@code Ser}, not null
1243      */
1244     @java.io.Serial
1245     private Object writeReplace() {
1246         return new Ser(Ser.YEAR_MONTH_TYPE, this);
1247     }
1248 
1249     /**
1250      * Defend against malicious streams.
1251      *
1252      * @param s the stream to read
1253      * @throws InvalidObjectException always
1254      */
1255     @java.io.Serial
1256     private void readObject(ObjectInputStream s) throws InvalidObjectException {
1257         throw new InvalidObjectException("Deserialization via serialization delegate");
1258     }
1259 
1260     void writeExternal(DataOutput out) throws IOException {
1261         out.writeInt(year);
1262         out.writeByte(month);
1263     }
1264 
1265     static YearMonth readExternal(DataInput in) throws IOException {
1266         int year = in.readInt();
1267         byte month = in.readByte();
1268         return YearMonth.of(year, month);
1269     }
1270 
1271 }