src/share/classes/java/time/YearMonth.java

Print this page




  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.temporal;
  63 
  64 import static java.time.temporal.ChronoField.EPOCH_MONTH;
  65 import static java.time.temporal.ChronoField.ERA;
  66 import static java.time.temporal.ChronoField.MONTH_OF_YEAR;
  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.MONTHS;
  70 
  71 import java.io.DataInput;
  72 import java.io.DataOutput;
  73 import java.io.IOException;
  74 import java.io.InvalidObjectException;
  75 import java.io.ObjectStreamException;
  76 import java.io.Serializable;
  77 import java.time.Clock;
  78 import java.time.DateTimeException;
  79 import java.time.LocalDate;
  80 import java.time.Month;
  81 import java.time.ZoneId;
  82 import java.time.format.DateTimeFormatter;
  83 import java.time.format.DateTimeFormatterBuilder;
  84 import java.time.format.DateTimeParseException;
  85 import java.time.format.SignStyle;











  86 import java.util.Objects;
  87 
  88 /**
  89  * A year-month in the ISO-8601 calendar system, such as {@code 2007-12}.
  90  * <p>
  91  * {@code YearMonth} is an immutable date-time object that represents the combination
  92  * of a year and month. Any field that can be derived from a year and month, such as
  93  * quarter-of-year, can be obtained.
  94  * <p>
  95  * This class does not store or represent a day, time or time-zone.
  96  * For example, the value "October 2007" can be stored in a {@code YearMonth}.
  97  * <p>
  98  * The ISO-8601 calendar system is the modern civil calendar system used today
  99  * in most of the world. It is equivalent to the proleptic Gregorian calendar
 100  * system, in which today's rules for leap years are applied for all time.
 101  * For most applications written today, the ISO-8601 rules are entirely suitable.
 102  * However, any application that makes use of historical dates, and requires them
 103  * to be accurate will find the ISO-8601 approach unsuitable.
 104  *
 105  * <h3>Specification for implementors</h3>


 195     }
 196 
 197     /**
 198      * Obtains an instance of {@code YearMonth} from a year and month.
 199      *
 200      * @param year  the year to represent, from MIN_YEAR to MAX_YEAR
 201      * @param month  the month-of-year to represent, from 1 (January) to 12 (December)
 202      * @return the year-month, not null
 203      * @throws DateTimeException if either field value is invalid
 204      */
 205     public static YearMonth of(int year, int month) {
 206         YEAR.checkValidValue(year);
 207         MONTH_OF_YEAR.checkValidValue(month);
 208         return new YearMonth(year, month);
 209     }
 210 
 211     //-----------------------------------------------------------------------
 212     /**
 213      * Obtains an instance of {@code YearMonth} from a temporal object.
 214      * <p>
 215      * A {@code TemporalAccessor} represents some form of date and time information.
 216      * This factory converts the arbitrary temporal object to an instance of {@code YearMonth}.

 217      * <p>
 218      * The conversion extracts the {@link ChronoField#YEAR YEAR} and
 219      * {@link ChronoField#MONTH_OF_YEAR MONTH_OF_YEAR} fields.
 220      * The extraction is only permitted if the temporal object has an ISO
 221      * chronology, or can be converted to a {@code LocalDate}.
 222      * <p>
 223      * This method matches the signature of the functional interface {@link TemporalQuery}
 224      * allowing it to be used in queries via method reference, {@code YearMonth::from}.
 225      *
 226      * @param temporal  the temporal object to convert, not null
 227      * @return the year-month, not null
 228      * @throws DateTimeException if unable to convert to a {@code YearMonth}
 229      */
 230     public static YearMonth from(TemporalAccessor temporal) {
 231         if (temporal instanceof YearMonth) {
 232             return (YearMonth) temporal;
 233         }
 234         try {
 235             if (ISOChrono.INSTANCE.equals(Chrono.from(temporal)) == false) {
 236                 temporal = LocalDate.from(temporal);
 237             }
 238             return of(temporal.get(YEAR), temporal.get(MONTH_OF_YEAR));
 239         } catch (DateTimeException ex) {
 240             throw new DateTimeException("Unable to obtain YearMonth from TemporalAccessor: " + temporal.getClass(), ex);
 241         }
 242     }
 243 
 244     //-----------------------------------------------------------------------
 245     /**
 246      * Obtains an instance of {@code YearMonth} from a text string such as {@code 2007-12}.
 247      * <p>
 248      * The string must represent a valid year-month.
 249      * The format must be {@code yyyy-MM}.
 250      * Years outside the range 0000 to 9999 must be prefixed by the plus or minus symbol.
 251      *
 252      * @param text  the text to parse such as "2007-12", not null
 253      * @return the parsed year-month, not null
 254      * @throws DateTimeParseException if the text cannot be parsed
 255      */


 291      * @param newYear  the year to represent, validated from MIN_YEAR to MAX_YEAR
 292      * @param newMonth  the month-of-year to represent, validated not null
 293      * @return the year-month, not null
 294      */
 295     private YearMonth with(int newYear, int newMonth) {
 296         if (year == newYear && month == newMonth) {
 297             return this;
 298         }
 299         return new YearMonth(newYear, newMonth);
 300     }
 301 
 302     //-----------------------------------------------------------------------
 303     /**
 304      * Checks if the specified field is supported.
 305      * <p>
 306      * This checks if this year-month can be queried for the specified field.
 307      * If false, then calling the {@link #range(TemporalField) range} and
 308      * {@link #get(TemporalField) get} methods will throw an exception.
 309      * <p>
 310      * If the field is a {@link ChronoField} then the query is implemented here.
 311      * The {@link #isSupported(TemporalField) supported fields} will return valid
 312      * values based on this date-time.
 313      * The supported fields are:
 314      * <ul>
 315      * <li>{@code MONTH_OF_YEAR}
 316      * <li>{@code EPOCH_MONTH}
 317      * <li>{@code YEAR_OF_ERA}
 318      * <li>{@code YEAR}
 319      * <li>{@code ERA}
 320      * </ul>
 321      * All other {@code ChronoField} instances will return false.
 322      * <p>
 323      * If the field is not a {@code ChronoField}, then the result of this method
 324      * is obtained by invoking {@code TemporalField.doIsSupported(TemporalAccessor)}
 325      * passing {@code this} as the argument.
 326      * Whether the field is supported is determined by the field.
 327      *
 328      * @param field  the field to check, null returns false
 329      * @return true if the field is supported on this year-month, false if not
 330      */
 331     @Override
 332     public boolean isSupported(TemporalField field) {
 333         if (field instanceof ChronoField) {
 334             return field == YEAR || field == MONTH_OF_YEAR ||
 335                     field == EPOCH_MONTH || field == YEAR_OF_ERA || field == ERA;
 336         }
 337         return field != null && field.doIsSupported(this);
 338     }
 339 
 340     /**
 341      * Gets the range of valid values for the specified field.
 342      * <p>
 343      * The range object expresses the minimum and maximum valid values for a field.
 344      * This year-month is used to enhance the accuracy of the returned range.
 345      * If it is not possible to return the range, because the field is not supported
 346      * or for some other reason, an exception is thrown.
 347      * <p>
 348      * If the field is a {@link ChronoField} then the query is implemented here.
 349      * The {@link #isSupported(TemporalField) supported fields} will return
 350      * appropriate range instances.
 351      * All other {@code ChronoField} instances will throw a {@code DateTimeException}.
 352      * <p>
 353      * If the field is not a {@code ChronoField}, then the result of this method
 354      * is obtained by invoking {@code TemporalField.doRange(TemporalAccessor)}
 355      * passing {@code this} as the argument.
 356      * Whether the range can be obtained is determined by the field.
 357      *
 358      * @param field  the field to query the range for, not null
 359      * @return the range of valid values for the field, not null
 360      * @throws DateTimeException if the range for the field cannot be obtained
 361      */
 362     @Override
 363     public ValueRange range(TemporalField field) {
 364         if (field == YEAR_OF_ERA) {
 365             return (getYear() <= 0 ? ValueRange.of(1, Year.MAX_VALUE + 1) : ValueRange.of(1, Year.MAX_VALUE));
 366         }
 367         return Temporal.super.range(field);
 368     }
 369 
 370     /**
 371      * Gets the value of the specified field from this year-month as an {@code int}.
 372      * <p>
 373      * This queries this year-month for the value for the specified field.
 374      * The returned value will always be within the valid range of values for the field.
 375      * If it is not possible to return the value, because the field is not supported
 376      * or for some other reason, an exception is thrown.
 377      * <p>
 378      * If the field is a {@link ChronoField} then the query is implemented here.
 379      * The {@link #isSupported(TemporalField) supported fields} will return valid
 380      * values based on this year-month, except {@code EPOCH_MONTH} which is too
 381      * large to fit in an {@code int} and throw a {@code DateTimeException}.
 382      * All other {@code ChronoField} instances will throw a {@code DateTimeException}.
 383      * <p>
 384      * If the field is not a {@code ChronoField}, then the result of this method
 385      * is obtained by invoking {@code TemporalField.doGet(TemporalAccessor)}
 386      * passing {@code this} as the argument. Whether the value can be obtained,
 387      * and what the value represents, is determined by the field.
 388      *
 389      * @param field  the field to get, not null
 390      * @return the value for the field
 391      * @throws DateTimeException if a value for the field cannot be obtained
 392      * @throws ArithmeticException if numeric overflow occurs
 393      */
 394     @Override  // override for Javadoc
 395     public int get(TemporalField field) {
 396         return range(field).checkValidIntValue(getLong(field), field);
 397     }
 398 
 399     /**
 400      * Gets the value of the specified field from this year-month as a {@code long}.
 401      * <p>
 402      * This queries this year-month for the value for the specified field.
 403      * If it is not possible to return the value, because the field is not supported
 404      * or for some other reason, an exception is thrown.
 405      * <p>
 406      * If the field is a {@link ChronoField} then the query is implemented here.
 407      * The {@link #isSupported(TemporalField) supported fields} will return valid
 408      * values based on this year-month.
 409      * All other {@code ChronoField} instances will throw a {@code DateTimeException}.
 410      * <p>
 411      * If the field is not a {@code ChronoField}, then the result of this method
 412      * is obtained by invoking {@code TemporalField.doGet(TemporalAccessor)}
 413      * passing {@code this} as the argument. Whether the value can be obtained,
 414      * and what the value represents, is determined by the field.
 415      *
 416      * @param field  the field to get, not null
 417      * @return the value for the field
 418      * @throws DateTimeException if a value for the field cannot be obtained
 419      * @throws ArithmeticException if numeric overflow occurs
 420      */
 421     @Override
 422     public long getLong(TemporalField field) {
 423         if (field instanceof ChronoField) {
 424             switch ((ChronoField) field) {
 425                 case MONTH_OF_YEAR: return month;
 426                 case EPOCH_MONTH: return getEpochMonth();
 427                 case YEAR_OF_ERA: return (year < 1 ? 1 - year : year);
 428                 case YEAR: return year;
 429                 case ERA: return (year < 1 ? 0 : 1);
 430             }
 431             throw new DateTimeException("Unsupported field: " + field.getName());
 432         }
 433         return field.doGet(this);
 434     }
 435 
 436     private long getEpochMonth() {
 437         return ((year - 1970) * 12L) + (month - 1);
 438     }
 439 
 440     //-----------------------------------------------------------------------
 441     /**
 442      * Gets the year field.
 443      * <p>
 444      * This method returns the primitive {@code int} value for the year.
 445      * <p>
 446      * The year returned by this method is proleptic as per {@code get(YEAR)}.
 447      *
 448      * @return the year, from MIN_YEAR to MAX_YEAR
 449      */
 450     public int getYear() {
 451         return year;
 452     }
 453 
 454     /**














 455      * Gets the month-of-year field using the {@code Month} enum.
 456      * <p>
 457      * This method returns the enum {@link Month} for the month.
 458      * This avoids confusion as to what {@code int} values mean.
 459      * If you need access to the primitive {@code int} value then the enum
 460      * provides the {@link Month#getValue() int value}.
 461      *
 462      * @return the month-of-year, not null

 463      */
 464     public Month getMonth() {
 465         return Month.of(month);
 466     }
 467 
 468     //-----------------------------------------------------------------------
 469     /**
 470      * Checks if the year is a leap year, according to the ISO proleptic
 471      * calendar system rules.
 472      * <p>
 473      * This method applies the current rules for leap years across the whole time-line.
 474      * In general, a year is a leap year if it is divisible by four without
 475      * remainder. However, years divisible by 100, are not leap years, with
 476      * the exception of years divisible by 400 which are.
 477      * <p>
 478      * For example, 1904 is a leap year it is divisible by 4.
 479      * 1900 was not a leap year as it is divisible by 100, however 2000 was a
 480      * leap year as it is divisible by 400.
 481      * <p>
 482      * The calculation is proleptic - applying the same rules into the far future and far past.
 483      * This is historically inaccurate, but is correct for the ISO-8601 standard.
 484      *
 485      * @return true if the year is leap, false otherwise
 486      */
 487     public boolean isLeapYear() {
 488         return ISOChrono.INSTANCE.isLeapYear(year);
 489     }
 490 
 491     /**
 492      * Checks if the day-of-month is valid for this year-month.
 493      * <p>
 494      * This method checks whether this year and month and the input day form
 495      * a valid date.
 496      *
 497      * @param dayOfMonth  the day-of-month to validate, from 1 to 31, invalid value returns false
 498      * @return true if the day is valid for this year-month
 499      */
 500     public boolean isValidDay(int dayOfMonth) {
 501         return dayOfMonth >= 1 && dayOfMonth <= lengthOfMonth();
 502     }
 503 
 504     /**
 505      * Returns the length of the month, taking account of the year.
 506      * <p>
 507      * This returns the length of the month in days.
 508      * For example, a date in January would return 31.


 511      */
 512     public int lengthOfMonth() {
 513         return getMonth().length(isLeapYear());
 514     }
 515 
 516     /**
 517      * Returns the length of the year.
 518      * <p>
 519      * This returns the length of the year in days, either 365 or 366.
 520      *
 521      * @return 366 if the year is leap, 365 otherwise
 522      */
 523     public int lengthOfYear() {
 524         return (isLeapYear() ? 366 : 365);
 525     }
 526 
 527     //-----------------------------------------------------------------------
 528     /**
 529      * Returns an adjusted copy of this year-month.
 530      * <p>
 531      * This returns a new {@code YearMonth}, based on this one, with the year-month adjusted.
 532      * The adjustment takes place using the specified adjuster strategy object.
 533      * Read the documentation of the adjuster to understand what adjustment will be made.
 534      * <p>
 535      * A simple adjuster might simply set the one of the fields, such as the year field.
 536      * A more complex adjuster might set the year-month to the next month that
 537      * Halley's comet will pass the Earth.
 538      * <p>
 539      * The result of this method is obtained by invoking the
 540      * {@link TemporalAdjuster#adjustInto(Temporal)} method on the
 541      * specified adjuster passing {@code this} as the argument.
 542      * <p>
 543      * This instance is immutable and unaffected by this method call.
 544      *
 545      * @param adjuster the adjuster to use, not null
 546      * @return a {@code YearMonth} based on {@code this} with the adjustment made, not null
 547      * @throws DateTimeException if the adjustment cannot be made
 548      * @throws ArithmeticException if numeric overflow occurs
 549      */
 550     @Override
 551     public YearMonth with(TemporalAdjuster adjuster) {
 552         return (YearMonth) adjuster.adjustInto(this);
 553     }
 554 
 555     /**
 556      * Returns a copy of this year-month with the specified field set to a new value.
 557      * <p>
 558      * This returns a new {@code YearMonth}, based on this one, with the value
 559      * for the specified field changed.
 560      * This can be used to change any supported field, such as the year or month.
 561      * If it is not possible to set the value, because the field is not supported or for
 562      * some other reason, an exception is thrown.
 563      * <p>
 564      * If the field is a {@link ChronoField} then the adjustment is implemented here.
 565      * The supported fields behave as follows:
 566      * <ul>
 567      * <li>{@code MONTH_OF_YEAR} -
 568      *  Returns a {@code YearMonth} with the specified month-of-year.
 569      *  The year will be unchanged.
 570      * <li>{@code EPOCH_MONTH} -
 571      *  Returns a {@code YearMonth} with the specified epoch-month.
 572      *  This completely replaces the year and month of this object.
 573      * <li>{@code YEAR_OF_ERA} -
 574      *  Returns a {@code YearMonth} with the specified year-of-era
 575      *  The month and era will be unchanged.
 576      * <li>{@code YEAR} -
 577      *  Returns a {@code YearMonth} with the specified year.
 578      *  The month will be unchanged.
 579      * <li>{@code ERA} -
 580      *  Returns a {@code YearMonth} with the specified era.
 581      *  The month and year-of-era will be unchanged.
 582      * </ul>
 583      * <p>
 584      * In all cases, if the new value is outside the valid range of values for the field
 585      * then a {@code DateTimeException} will be thrown.
 586      * <p>
 587      * All other {@code ChronoField} instances will throw a {@code DateTimeException}.
 588      * <p>
 589      * If the field is not a {@code ChronoField}, then the result of this method
 590      * is obtained by invoking {@code TemporalField.doWith(Temporal, long)}
 591      * passing {@code this} as the argument. In this case, the field determines
 592      * whether and how to adjust the instant.
 593      * <p>
 594      * This instance is immutable and unaffected by this method call.
 595      *
 596      * @param field  the field to set in the result, not null
 597      * @param newValue  the new value of the field in the result
 598      * @return a {@code YearMonth} based on {@code this} with the specified field set, not null
 599      * @throws DateTimeException if the field cannot be set
 600      * @throws ArithmeticException if numeric overflow occurs
 601      */
 602     @Override
 603     public YearMonth with(TemporalField field, long newValue) {
 604         if (field instanceof ChronoField) {
 605             ChronoField f = (ChronoField) field;
 606             f.checkValidValue(newValue);
 607             switch (f) {
 608                 case MONTH_OF_YEAR: return withMonth((int) newValue);
 609                 case EPOCH_MONTH: return plusMonths(newValue - getLong(EPOCH_MONTH));
 610                 case YEAR_OF_ERA: return withYear((int) (year < 1 ? 1 - newValue : newValue));
 611                 case YEAR: return withYear((int) newValue);
 612                 case ERA: return (getLong(ERA) == newValue ? this : withYear(1 - year));
 613             }
 614             throw new DateTimeException("Unsupported field: " + field.getName());
 615         }
 616         return field.doWith(this, newValue);
 617     }
 618 
 619     //-----------------------------------------------------------------------
 620     /**
 621      * Returns a copy of this {@code YearMonth} with the year altered.
 622      * <p>
 623      * This instance is immutable and unaffected by this method call.
 624      *
 625      * @param year  the year to set in the returned year-month, from MIN_YEAR to MAX_YEAR
 626      * @return a {@code YearMonth} based on this year-month with the requested year, not null
 627      * @throws DateTimeException if the year value is invalid
 628      */
 629     public YearMonth withYear(int year) {
 630         YEAR.checkValidValue(year);
 631         return with(year, month);
 632     }
 633 
 634     /**
 635      * Returns a copy of this {@code YearMonth} with the month-of-year altered.
 636      * <p>
 637      * This instance is immutable and unaffected by this method call.
 638      *
 639      * @param month  the month-of-year to set in the returned year-month, from 1 (January) to 12 (December)
 640      * @return a {@code YearMonth} based on this year-month with the requested month, not null
 641      * @throws DateTimeException if the month-of-year value is invalid
 642      */
 643     public YearMonth withMonth(int month) {
 644         MONTH_OF_YEAR.checkValidValue(month);
 645         return with(year, month);
 646     }
 647 
 648     //-----------------------------------------------------------------------
 649     /**
 650      * Returns a copy of this year-month with the specified period added.
 651      * <p>
 652      * This method returns a new year-month based on this year-month with the specified period added.
 653      * The adder is typically {@link java.time.Period} but may be any other type implementing
 654      * the {@link TemporalAdder} interface.
 655      * The calculation is delegated to the specified adjuster, which typically calls
 656      * back to {@link #plus(long, TemporalUnit)}.




 657      * <p>
 658      * This instance is immutable and unaffected by this method call.
 659      *
 660      * @param adder  the adder to use, not null
 661      * @return a {@code YearMonth} based on this year-month with the addition made, not null
 662      * @throws DateTimeException if the addition cannot be made
 663      * @throws ArithmeticException if numeric overflow occurs
 664      */
 665     @Override
 666     public YearMonth plus(TemporalAdder adder) {
 667         return (YearMonth) adder.addTo(this);
 668     }
 669 
 670     /**
 671      * {@inheritDoc}
 672      * @throws DateTimeException {@inheritDoc}
 673      * @throws ArithmeticException {@inheritDoc}













































 674      */
 675     @Override
 676     public YearMonth plus(long amountToAdd, TemporalUnit unit) {
 677         if (unit instanceof ChronoUnit) {
 678             switch ((ChronoUnit) unit) {
 679                 case MONTHS: return plusMonths(amountToAdd);
 680                 case YEARS: return plusYears(amountToAdd);
 681                 case DECADES: return plusYears(Math.multiplyExact(amountToAdd, 10));
 682                 case CENTURIES: return plusYears(Math.multiplyExact(amountToAdd, 100));
 683                 case MILLENNIA: return plusYears(Math.multiplyExact(amountToAdd, 1000));
 684                 case ERAS: return with(ERA, Math.addExact(getLong(ERA), amountToAdd));
 685             }
 686             throw new DateTimeException("Unsupported unit: " + unit.getName());
 687         }
 688         return unit.doPlus(this, amountToAdd);
 689     }
 690 
 691     /**
 692      * Returns a copy of this year-month with the specified period in years added.
 693      * <p>
 694      * This instance is immutable and unaffected by this method call.
 695      *
 696      * @param yearsToAdd  the years to add, may be negative
 697      * @return a {@code YearMonth} based on this year-month with the years added, not null
 698      * @throws DateTimeException if the result exceeds the supported range
 699      */
 700     public YearMonth plusYears(long yearsToAdd) {
 701         if (yearsToAdd == 0) {
 702             return this;
 703         }
 704         int newYear = YEAR.checkValidIntValue(year + yearsToAdd);  // safe overflow
 705         return with(newYear, month);
 706     }
 707 
 708     /**


 710      * <p>
 711      * This instance is immutable and unaffected by this method call.
 712      *
 713      * @param monthsToAdd  the months to add, may be negative
 714      * @return a {@code YearMonth} based on this year-month with the months added, not null
 715      * @throws DateTimeException if the result exceeds the supported range
 716      */
 717     public YearMonth plusMonths(long monthsToAdd) {
 718         if (monthsToAdd == 0) {
 719             return this;
 720         }
 721         long monthCount = year * 12L + (month - 1);
 722         long calcMonths = monthCount + monthsToAdd;  // safe overflow
 723         int newYear = YEAR.checkValidIntValue(Math.floorDiv(calcMonths, 12));
 724         int newMonth = (int)Math.floorMod(calcMonths, 12) + 1;
 725         return with(newYear, newMonth);
 726     }
 727 
 728     //-----------------------------------------------------------------------
 729     /**
 730      * Returns a copy of this year-month with the specified period subtracted.
 731      * <p>
 732      * This method returns a new year-month based on this year-month with the specified period subtracted.
 733      * The subtractor is typically {@link java.time.Period} but may be any other type implementing
 734      * the {@link TemporalSubtractor} interface.
 735      * The calculation is delegated to the specified adjuster, which typically calls
 736      * back to {@link #minus(long, TemporalUnit)}.




 737      * <p>
 738      * This instance is immutable and unaffected by this method call.
 739      *
 740      * @param subtractor  the subtractor to use, not null
 741      * @return a {@code YearMonth} based on this year-month with the subtraction made, not null
 742      * @throws DateTimeException if the subtraction cannot be made
 743      * @throws ArithmeticException if numeric overflow occurs
 744      */
 745     @Override
 746     public YearMonth minus(TemporalSubtractor subtractor) {
 747         return (YearMonth) subtractor.subtractFrom(this);
 748     }
 749 
 750     /**
 751      * {@inheritDoc}
 752      * @throws DateTimeException {@inheritDoc}
 753      * @throws ArithmeticException {@inheritDoc}













 754      */
 755     @Override
 756     public YearMonth minus(long amountToSubtract, TemporalUnit unit) {
 757         return (amountToSubtract == Long.MIN_VALUE ? plus(Long.MAX_VALUE, unit).plus(1, unit) : plus(-amountToSubtract, unit));
 758     }
 759 
 760     /**
 761      * Returns a copy of this year-month with the specified period in years subtracted.
 762      * <p>
 763      * This instance is immutable and unaffected by this method call.
 764      *
 765      * @param yearsToSubtract  the years to subtract, may be negative
 766      * @return a {@code YearMonth} based on this year-month with the years subtracted, not null
 767      * @throws DateTimeException if the result exceeds the supported range
 768      */
 769     public YearMonth minusYears(long yearsToSubtract) {
 770         return (yearsToSubtract == Long.MIN_VALUE ? plusYears(Long.MAX_VALUE).plusYears(1) : plusYears(-yearsToSubtract));
 771     }
 772 
 773     /**


 788      * Queries this year-month using the specified query.
 789      * <p>
 790      * This queries this year-month using the specified query strategy object.
 791      * The {@code TemporalQuery} object defines the logic to be used to
 792      * obtain the result. Read the documentation of the query to understand
 793      * what the result of this method will be.
 794      * <p>
 795      * The result of this method is obtained by invoking the
 796      * {@link TemporalQuery#queryFrom(TemporalAccessor)} method on the
 797      * specified query passing {@code this} as the argument.
 798      *
 799      * @param <R> the type of the result
 800      * @param query  the query to invoke, not null
 801      * @return the query result, null may be returned (defined by the query)
 802      * @throws DateTimeException if unable to query (defined by the query)
 803      * @throws ArithmeticException if numeric overflow occurs (defined by the query)
 804      */
 805     @SuppressWarnings("unchecked")
 806     @Override
 807     public <R> R query(TemporalQuery<R> query) {
 808         if (query == Queries.chrono()) {
 809             return (R) ISOChrono.INSTANCE;
 810         } else if (query == Queries.precision()) {
 811             return (R) MONTHS;
 812         }
 813         return Temporal.super.query(query);
 814     }
 815 
 816     /**
 817      * Adjusts the specified temporal object to have this year-month.
 818      * <p>
 819      * This returns a temporal object of the same observable type as the input
 820      * with the year and month changed to be the same as this.
 821      * <p>
 822      * The adjustment is equivalent to using {@link Temporal#with(TemporalField, long)}
 823      * passing {@link ChronoField#EPOCH_MONTH} as the field.
 824      * If the specified temporal object does not use the ISO calendar system then
 825      * a {@code DateTimeException} is thrown.
 826      * <p>
 827      * In most cases, it is clearer to reverse the calling pattern by using
 828      * {@link Temporal#with(TemporalAdjuster)}:
 829      * <pre>
 830      *   // these two lines are equivalent, but the second approach is recommended
 831      *   temporal = thisYearMonth.adjustInto(temporal);
 832      *   temporal = temporal.with(thisYearMonth);
 833      * </pre>
 834      * <p>
 835      * This instance is immutable and unaffected by this method call.
 836      *
 837      * @param temporal  the target object to be adjusted, not null
 838      * @return the adjusted object, not null
 839      * @throws DateTimeException if unable to make the adjustment
 840      * @throws ArithmeticException if numeric overflow occurs
 841      */
 842     @Override
 843     public Temporal adjustInto(Temporal temporal) {
 844         if (Chrono.from(temporal).equals(ISOChrono.INSTANCE) == false) {
 845             throw new DateTimeException("Adjustment only supported on ISO date-time");
 846         }
 847         return temporal.with(EPOCH_MONTH, getEpochMonth());
 848     }
 849 
 850     /**
 851      * Calculates the period between this year-month and another year-month in
 852      * terms of the specified unit.
 853      * <p>
 854      * This calculates the period between two year-months in terms of a single unit.
 855      * The start and end points are {@code this} and the specified year-month.
 856      * The result will be negative if the end is before the start.
 857      * The {@code Temporal} passed to this method must be a {@code YearMonth}.
 858      * For example, the period in years between two year-months can be calculated
 859      * using {@code startYearMonth.periodUntil(endYearMonth, YEARS)}.
 860      * <p>
 861      * The calculation returns a whole number, representing the number of
 862      * complete units between the two year-months.
 863      * For example, the period in decades between 2012-06 and 2032-05
 864      * will only be one decade as it is one month short of two decades.
 865      * <p>
 866      * This method operates in association with {@link TemporalUnit#between}.
 867      * The result of this method is a {@code long} representing the amount of
 868      * the specified unit. By contrast, the result of {@code between} is an
 869      * object that can be used directly in addition/subtraction:
 870      * <pre>
 871      *   long period = start.periodUntil(end, YEARS);   // this method
 872      *   dateTime.plus(YEARS.between(start, end));      // use in plus/minus

 873      * </pre>

 874      * <p>
 875      * The calculation is implemented in this method for {@link ChronoUnit}.
 876      * The units {@code MONTHS}, {@code YEARS}, {@code DECADES},
 877      * {@code CENTURIES}, {@code MILLENNIA} and {@code ERAS} are supported.
 878      * Other {@code ChronoUnit} values will throw an exception.
 879      * <p>
 880      * If the unit is not a {@code ChronoUnit}, then the result of this method
 881      * is obtained by invoking {@code TemporalUnit.between(Temporal, Temporal)}
 882      * passing {@code this} as the first argument and the input temporal as
 883      * the second argument.
 884      * <p>
 885      * This instance is immutable and unaffected by this method call.
 886      *
 887      * @param endYearMonth  the end year-month, which must be a {@code YearMonth}, not null
 888      * @param unit  the unit to measure the period in, not null
 889      * @return the amount of the period between this year-month and the end year-month
 890      * @throws DateTimeException if the period cannot be calculated
 891      * @throws ArithmeticException if numeric overflow occurs
 892      */
 893     @Override
 894     public long periodUntil(Temporal endYearMonth, TemporalUnit unit) {
 895         if (endYearMonth instanceof YearMonth == false) {
 896             Objects.requireNonNull(endYearMonth, "endYearMonth");
 897             throw new DateTimeException("Unable to calculate period between objects of two different types");
 898         }
 899         YearMonth end = (YearMonth) endYearMonth;
 900         if (unit instanceof ChronoUnit) {
 901             long monthsUntil = end.getEpochMonth() - getEpochMonth();  // no overflow
 902             switch ((ChronoUnit) unit) {
 903                 case MONTHS: return monthsUntil;
 904                 case YEARS: return monthsUntil / 12;
 905                 case DECADES: return monthsUntil / 120;
 906                 case CENTURIES: return monthsUntil / 1200;
 907                 case MILLENNIA: return monthsUntil / 12000;
 908                 case ERAS: return end.getLong(ERA) - getLong(ERA);
 909             }
 910             throw new DateTimeException("Unsupported unit: " + unit.getName());
 911         }
 912         return unit.between(this, endYearMonth).getAmount();
 913     }
 914 
 915     //-----------------------------------------------------------------------
 916     /**
 917      * Returns a date formed from this year-month at the specified day-of-month.


 918      * <p>
 919      * This combines this year-month and the specified day-of-month to form a {@code LocalDate}.
 920      * The day-of-month value must be valid for the year-month.
 921      * <p>
 922      * This method can be used as part of a chain to produce a date:
 923      * <pre>
 924      *  LocalDate date = year.atMonth(month).atDay(day);
 925      * </pre>
 926      * <p>
 927      * This instance is immutable and unaffected by this method call.
 928      *
 929      * @param dayOfMonth  the day-of-month to use, from 1 to 31
 930      * @return the date formed from this year-month and the specified day, not null
 931      * @throws DateTimeException when the day is invalid for the year-month
 932      * @see #isValidDay(int)
 933      */
 934     public LocalDate atDay(int dayOfMonth) {
 935         return LocalDate.of(year, month, dayOfMonth);
 936     }
 937 


















 938     //-----------------------------------------------------------------------
 939     /**
 940      * Compares this year-month to another year-month.
 941      * <p>
 942      * The comparison is based first on the value of the year, then on the value of the month.
 943      * It is "consistent with equals", as defined by {@link Comparable}.
 944      *
 945      * @param other  the other year-month to compare to, not null
 946      * @return the comparator value, negative if less, positive if greater
 947      */
 948     @Override
 949     public int compareTo(YearMonth other) {
 950         int cmp = (year - other.year);
 951         if (cmp == 0) {
 952             cmp = (month - other.month);
 953         }
 954         return cmp;
 955     }
 956 
 957     /**


1018         int absYear = Math.abs(year);
1019         StringBuilder buf = new StringBuilder(9);
1020         if (absYear < 1000) {
1021             if (year < 0) {
1022                 buf.append(year - 10000).deleteCharAt(1);
1023             } else {
1024                 buf.append(year + 10000).deleteCharAt(0);
1025             }
1026         } else {
1027             buf.append(year);
1028         }
1029         return buf.append(month < 10 ? "-0" : "-")
1030             .append(month)
1031             .toString();
1032     }
1033 
1034     /**
1035      * Outputs this year-month as a {@code String} using the formatter.
1036      * <p>
1037      * This year-month will be passed to the formatter
1038      * {@link DateTimeFormatter#print(TemporalAccessor) print method}.
1039      *
1040      * @param formatter  the formatter to use, not null
1041      * @return the formatted year-month string, not null
1042      * @throws DateTimeException if an error occurs during printing
1043      */
1044     public String toString(DateTimeFormatter formatter) {
1045         Objects.requireNonNull(formatter, "formatter");
1046         return formatter.print(this);
1047     }
1048 
1049     //-----------------------------------------------------------------------
1050     /**
1051      * Writes the object using a
1052      * <a href="../../../serialized-form.html#java.time.temporal.Ser">dedicated serialized form</a>.
1053      * <pre>
1054      *  out.writeByte(5);  // identifies this as a Year
1055      *  out.writeInt(year);
1056      *  out.writeByte(month);
1057      * </pre>
1058      *
1059      * @return the instance of {@code Ser}, not null
1060      */
1061     private Object writeReplace() {
1062         return new Ser(Ser.YEAR_MONTH_TYPE, this);
1063     }
1064 
1065     /**
1066      * Defend against malicious streams.
1067      * @return never
1068      * @throws InvalidObjectException always
1069      */
1070     private Object readResolve() throws ObjectStreamException {
1071         throw new InvalidObjectException("Deserialization via serialization delegate");
1072     }
1073 
1074     void writeExternal(DataOutput out) throws IOException {


  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.EPOCH_MONTH;
  65 import static java.time.temporal.ChronoField.ERA;
  66 import static java.time.temporal.ChronoField.MONTH_OF_YEAR;
  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.MONTHS;
  70 
  71 import java.io.DataInput;
  72 import java.io.DataOutput;
  73 import java.io.IOException;
  74 import java.io.InvalidObjectException;
  75 import java.io.ObjectStreamException;
  76 import java.io.Serializable;
  77 import java.time.chrono.Chronology;
  78 import java.time.chrono.IsoChronology;



  79 import java.time.format.DateTimeFormatter;
  80 import java.time.format.DateTimeFormatterBuilder;
  81 import java.time.format.DateTimeParseException;
  82 import java.time.format.SignStyle;
  83 import java.time.temporal.ChronoField;
  84 import java.time.temporal.ChronoUnit;
  85 import java.time.temporal.Queries;
  86 import java.time.temporal.Temporal;
  87 import java.time.temporal.TemporalAccessor;
  88 import java.time.temporal.TemporalAdjuster;
  89 import java.time.temporal.TemporalAmount;
  90 import java.time.temporal.TemporalField;
  91 import java.time.temporal.TemporalQuery;
  92 import java.time.temporal.TemporalUnit;
  93 import java.time.temporal.ValueRange;
  94 import java.util.Objects;
  95 
  96 /**
  97  * A year-month in the ISO-8601 calendar system, such as {@code 2007-12}.
  98  * <p>
  99  * {@code YearMonth} is an immutable date-time object that represents the combination
 100  * of a year and month. Any field that can be derived from a year and month, such as
 101  * quarter-of-year, can be obtained.
 102  * <p>
 103  * This class does not store or represent a day, time or time-zone.
 104  * For example, the value "October 2007" can be stored in a {@code YearMonth}.
 105  * <p>
 106  * The ISO-8601 calendar system is the modern civil calendar system used today
 107  * in most of the world. It is equivalent to the proleptic Gregorian calendar
 108  * system, in which today's rules for leap years are applied for all time.
 109  * For most applications written today, the ISO-8601 rules are entirely suitable.
 110  * However, any application that makes use of historical dates, and requires them
 111  * to be accurate will find the ISO-8601 approach unsuitable.
 112  *
 113  * <h3>Specification for implementors</h3>


 203     }
 204 
 205     /**
 206      * Obtains an instance of {@code YearMonth} from a year and month.
 207      *
 208      * @param year  the year to represent, from MIN_YEAR to MAX_YEAR
 209      * @param month  the month-of-year to represent, from 1 (January) to 12 (December)
 210      * @return the year-month, not null
 211      * @throws DateTimeException if either field value is invalid
 212      */
 213     public static YearMonth of(int year, int month) {
 214         YEAR.checkValidValue(year);
 215         MONTH_OF_YEAR.checkValidValue(month);
 216         return new YearMonth(year, month);
 217     }
 218 
 219     //-----------------------------------------------------------------------
 220     /**
 221      * Obtains an instance of {@code YearMonth} from a temporal object.
 222      * <p>
 223      * This obtains a year-month based on the specified temporal.
 224      * A {@code TemporalAccessor} represents an arbitrary set of date and time information,
 225      * which this factory converts to an instance of {@code YearMonth}.
 226      * <p>
 227      * The conversion extracts the {@link ChronoField#YEAR YEAR} and
 228      * {@link ChronoField#MONTH_OF_YEAR MONTH_OF_YEAR} fields.
 229      * The extraction is only permitted if the temporal object has an ISO
 230      * chronology, or can be converted to a {@code LocalDate}.
 231      * <p>
 232      * This method matches the signature of the functional interface {@link TemporalQuery}
 233      * allowing it to be used in queries via method reference, {@code YearMonth::from}.
 234      *
 235      * @param temporal  the temporal object to convert, not null
 236      * @return the year-month, not null
 237      * @throws DateTimeException if unable to convert to a {@code YearMonth}
 238      */
 239     public static YearMonth from(TemporalAccessor temporal) {
 240         if (temporal instanceof YearMonth) {
 241             return (YearMonth) temporal;
 242         }
 243         try {
 244             if (IsoChronology.INSTANCE.equals(Chronology.from(temporal)) == false) {
 245                 temporal = LocalDate.from(temporal);
 246             }
 247             return of(temporal.get(YEAR), temporal.get(MONTH_OF_YEAR));
 248         } catch (DateTimeException ex) {
 249             throw new DateTimeException("Unable to obtain YearMonth from TemporalAccessor: " + temporal.getClass(), ex);
 250         }
 251     }
 252 
 253     //-----------------------------------------------------------------------
 254     /**
 255      * Obtains an instance of {@code YearMonth} from a text string such as {@code 2007-12}.
 256      * <p>
 257      * The string must represent a valid year-month.
 258      * The format must be {@code yyyy-MM}.
 259      * Years outside the range 0000 to 9999 must be prefixed by the plus or minus symbol.
 260      *
 261      * @param text  the text to parse such as "2007-12", not null
 262      * @return the parsed year-month, not null
 263      * @throws DateTimeParseException if the text cannot be parsed
 264      */


 300      * @param newYear  the year to represent, validated from MIN_YEAR to MAX_YEAR
 301      * @param newMonth  the month-of-year to represent, validated not null
 302      * @return the year-month, not null
 303      */
 304     private YearMonth with(int newYear, int newMonth) {
 305         if (year == newYear && month == newMonth) {
 306             return this;
 307         }
 308         return new YearMonth(newYear, newMonth);
 309     }
 310 
 311     //-----------------------------------------------------------------------
 312     /**
 313      * Checks if the specified field is supported.
 314      * <p>
 315      * This checks if this year-month can be queried for the specified field.
 316      * If false, then calling the {@link #range(TemporalField) range} and
 317      * {@link #get(TemporalField) get} methods will throw an exception.
 318      * <p>
 319      * If the field is a {@link ChronoField} then the query is implemented here.


 320      * The supported fields are:
 321      * <ul>
 322      * <li>{@code MONTH_OF_YEAR}
 323      * <li>{@code EPOCH_MONTH}
 324      * <li>{@code YEAR_OF_ERA}
 325      * <li>{@code YEAR}
 326      * <li>{@code ERA}
 327      * </ul>
 328      * All other {@code ChronoField} instances will return false.
 329      * <p>
 330      * If the field is not a {@code ChronoField}, then the result of this method
 331      * is obtained by invoking {@code TemporalField.isSupportedBy(TemporalAccessor)}
 332      * passing {@code this} as the argument.
 333      * Whether the field is supported is determined by the field.
 334      *
 335      * @param field  the field to check, null returns false
 336      * @return true if the field is supported on this year-month, false if not
 337      */
 338     @Override
 339     public boolean isSupported(TemporalField field) {
 340         if (field instanceof ChronoField) {
 341             return field == YEAR || field == MONTH_OF_YEAR ||
 342                     field == EPOCH_MONTH || field == YEAR_OF_ERA || field == ERA;
 343         }
 344         return field != null && field.isSupportedBy(this);
 345     }
 346 
 347     /**
 348      * Gets the range of valid values for the specified field.
 349      * <p>
 350      * The range object expresses the minimum and maximum valid values for a field.
 351      * This year-month is used to enhance the accuracy of the returned range.
 352      * If it is not possible to return the range, because the field is not supported
 353      * or for some other reason, an exception is thrown.
 354      * <p>
 355      * If the field is a {@link ChronoField} then the query is implemented here.
 356      * The {@link #isSupported(TemporalField) supported fields} will return
 357      * appropriate range instances.
 358      * All other {@code ChronoField} instances will throw a {@code DateTimeException}.
 359      * <p>
 360      * If the field is not a {@code ChronoField}, then the result of this method
 361      * is obtained by invoking {@code TemporalField.rangeRefinedBy(TemporalAccessor)}
 362      * passing {@code this} as the argument.
 363      * Whether the range can be obtained is determined by the field.
 364      *
 365      * @param field  the field to query the range for, not null
 366      * @return the range of valid values for the field, not null
 367      * @throws DateTimeException if the range for the field cannot be obtained
 368      */
 369     @Override
 370     public ValueRange range(TemporalField field) {
 371         if (field == YEAR_OF_ERA) {
 372             return (getYear() <= 0 ? ValueRange.of(1, Year.MAX_VALUE + 1) : ValueRange.of(1, Year.MAX_VALUE));
 373         }
 374         return Temporal.super.range(field);
 375     }
 376 
 377     /**
 378      * Gets the value of the specified field from this year-month as an {@code int}.
 379      * <p>
 380      * This queries this year-month for the value for the specified field.
 381      * The returned value will always be within the valid range of values for the field.
 382      * If it is not possible to return the value, because the field is not supported
 383      * or for some other reason, an exception is thrown.
 384      * <p>
 385      * If the field is a {@link ChronoField} then the query is implemented here.
 386      * The {@link #isSupported(TemporalField) supported fields} will return valid
 387      * values based on this year-month, except {@code EPOCH_MONTH} which is too
 388      * large to fit in an {@code int} and throw a {@code DateTimeException}.
 389      * All other {@code ChronoField} instances will throw a {@code DateTimeException}.
 390      * <p>
 391      * If the field is not a {@code ChronoField}, then the result of this method
 392      * is obtained by invoking {@code TemporalField.getFrom(TemporalAccessor)}
 393      * passing {@code this} as the argument. Whether the value can be obtained,
 394      * and what the value represents, is determined by the field.
 395      *
 396      * @param field  the field to get, not null
 397      * @return the value for the field
 398      * @throws DateTimeException if a value for the field cannot be obtained
 399      * @throws ArithmeticException if numeric overflow occurs
 400      */
 401     @Override  // override for Javadoc
 402     public int get(TemporalField field) {
 403         return range(field).checkValidIntValue(getLong(field), field);
 404     }
 405 
 406     /**
 407      * Gets the value of the specified field from this year-month as a {@code long}.
 408      * <p>
 409      * This queries this year-month for the value for the specified field.
 410      * If it is not possible to return the value, because the field is not supported
 411      * or for some other reason, an exception is thrown.
 412      * <p>
 413      * If the field is a {@link ChronoField} then the query is implemented here.
 414      * The {@link #isSupported(TemporalField) supported fields} will return valid
 415      * values based on this year-month.
 416      * All other {@code ChronoField} instances will throw a {@code DateTimeException}.
 417      * <p>
 418      * If the field is not a {@code ChronoField}, then the result of this method
 419      * is obtained by invoking {@code TemporalField.getFrom(TemporalAccessor)}
 420      * passing {@code this} as the argument. Whether the value can be obtained,
 421      * and what the value represents, is determined by the field.
 422      *
 423      * @param field  the field to get, not null
 424      * @return the value for the field
 425      * @throws DateTimeException if a value for the field cannot be obtained
 426      * @throws ArithmeticException if numeric overflow occurs
 427      */
 428     @Override
 429     public long getLong(TemporalField field) {
 430         if (field instanceof ChronoField) {
 431             switch ((ChronoField) field) {
 432                 case MONTH_OF_YEAR: return month;
 433                 case EPOCH_MONTH: return getEpochMonth();
 434                 case YEAR_OF_ERA: return (year < 1 ? 1 - year : year);
 435                 case YEAR: return year;
 436                 case ERA: return (year < 1 ? 0 : 1);
 437             }
 438             throw new DateTimeException("Unsupported field: " + field.getName());
 439         }
 440         return field.getFrom(this);
 441     }
 442 
 443     private long getEpochMonth() {
 444         return ((year - 1970) * 12L) + (month - 1);
 445     }
 446 
 447     //-----------------------------------------------------------------------
 448     /**
 449      * Gets the year field.
 450      * <p>
 451      * This method returns the primitive {@code int} value for the year.
 452      * <p>
 453      * The year returned by this method is proleptic as per {@code get(YEAR)}.
 454      *
 455      * @return the year, from MIN_YEAR to MAX_YEAR
 456      */
 457     public int getYear() {
 458         return year;
 459     }
 460 
 461     /**
 462      * Gets the month-of-year field from 1 to 12.
 463      * <p>
 464      * This method returns the month as an {@code int} from 1 to 12.
 465      * Application code is frequently clearer if the enum {@link Month}
 466      * is used by calling {@link #getMonth()}.
 467      *
 468      * @return the month-of-year, from 1 to 12
 469      * @see #getMonth()
 470      */
 471     public int getMonthValue() {
 472         return month;
 473     }
 474 
 475     /**
 476      * Gets the month-of-year field using the {@code Month} enum.
 477      * <p>
 478      * This method returns the enum {@link Month} for the month.
 479      * This avoids confusion as to what {@code int} values mean.
 480      * If you need access to the primitive {@code int} value then the enum
 481      * provides the {@link Month#getValue() int value}.
 482      *
 483      * @return the month-of-year, not null
 484      * @see #getMonthValue()
 485      */
 486     public Month getMonth() {
 487         return Month.of(month);
 488     }
 489 
 490     //-----------------------------------------------------------------------
 491     /**
 492      * Checks if the year is a leap year, according to the ISO proleptic
 493      * calendar system rules.
 494      * <p>
 495      * This method applies the current rules for leap years across the whole time-line.
 496      * In general, a year is a leap year if it is divisible by four without
 497      * remainder. However, years divisible by 100, are not leap years, with
 498      * the exception of years divisible by 400 which are.
 499      * <p>
 500      * For example, 1904 is a leap year it is divisible by 4.
 501      * 1900 was not a leap year as it is divisible by 100, however 2000 was a
 502      * leap year as it is divisible by 400.
 503      * <p>
 504      * The calculation is proleptic - applying the same rules into the far future and far past.
 505      * This is historically inaccurate, but is correct for the ISO-8601 standard.
 506      *
 507      * @return true if the year is leap, false otherwise
 508      */
 509     public boolean isLeapYear() {
 510         return IsoChronology.INSTANCE.isLeapYear(year);
 511     }
 512 
 513     /**
 514      * Checks if the day-of-month is valid for this year-month.
 515      * <p>
 516      * This method checks whether this year and month and the input day form
 517      * a valid date.
 518      *
 519      * @param dayOfMonth  the day-of-month to validate, from 1 to 31, invalid value returns false
 520      * @return true if the day is valid for this year-month
 521      */
 522     public boolean isValidDay(int dayOfMonth) {
 523         return dayOfMonth >= 1 && dayOfMonth <= lengthOfMonth();
 524     }
 525 
 526     /**
 527      * Returns the length of the month, taking account of the year.
 528      * <p>
 529      * This returns the length of the month in days.
 530      * For example, a date in January would return 31.


 533      */
 534     public int lengthOfMonth() {
 535         return getMonth().length(isLeapYear());
 536     }
 537 
 538     /**
 539      * Returns the length of the year.
 540      * <p>
 541      * This returns the length of the year in days, either 365 or 366.
 542      *
 543      * @return 366 if the year is leap, 365 otherwise
 544      */
 545     public int lengthOfYear() {
 546         return (isLeapYear() ? 366 : 365);
 547     }
 548 
 549     //-----------------------------------------------------------------------
 550     /**
 551      * Returns an adjusted copy of this year-month.
 552      * <p>
 553      * This returns a {@code YearMonth}, based on this one, with the year-month adjusted.
 554      * The adjustment takes place using the specified adjuster strategy object.
 555      * Read the documentation of the adjuster to understand what adjustment will be made.
 556      * <p>
 557      * A simple adjuster might simply set the one of the fields, such as the year field.
 558      * A more complex adjuster might set the year-month to the next month that
 559      * Halley's comet will pass the Earth.
 560      * <p>
 561      * The result of this method is obtained by invoking the
 562      * {@link TemporalAdjuster#adjustInto(Temporal)} method on the
 563      * specified adjuster passing {@code this} as the argument.
 564      * <p>
 565      * This instance is immutable and unaffected by this method call.
 566      *
 567      * @param adjuster the adjuster to use, not null
 568      * @return a {@code YearMonth} based on {@code this} with the adjustment made, not null
 569      * @throws DateTimeException if the adjustment cannot be made
 570      * @throws ArithmeticException if numeric overflow occurs
 571      */
 572     @Override
 573     public YearMonth with(TemporalAdjuster adjuster) {
 574         return (YearMonth) adjuster.adjustInto(this);
 575     }
 576 
 577     /**
 578      * Returns a copy of this year-month with the specified field set to a new value.
 579      * <p>
 580      * This returns a {@code YearMonth}, based on this one, with the value
 581      * for the specified field changed.
 582      * This can be used to change any supported field, such as the year or month.
 583      * If it is not possible to set the value, because the field is not supported or for
 584      * some other reason, an exception is thrown.
 585      * <p>
 586      * If the field is a {@link ChronoField} then the adjustment is implemented here.
 587      * The supported fields behave as follows:
 588      * <ul>
 589      * <li>{@code MONTH_OF_YEAR} -
 590      *  Returns a {@code YearMonth} with the specified month-of-year.
 591      *  The year will be unchanged.
 592      * <li>{@code EPOCH_MONTH} -
 593      *  Returns a {@code YearMonth} with the specified epoch-month.
 594      *  This completely replaces the year and month of this object.
 595      * <li>{@code YEAR_OF_ERA} -
 596      *  Returns a {@code YearMonth} with the specified year-of-era
 597      *  The month and era will be unchanged.
 598      * <li>{@code YEAR} -
 599      *  Returns a {@code YearMonth} with the specified year.
 600      *  The month will be unchanged.
 601      * <li>{@code ERA} -
 602      *  Returns a {@code YearMonth} with the specified era.
 603      *  The month and year-of-era will be unchanged.
 604      * </ul>
 605      * <p>
 606      * In all cases, if the new value is outside the valid range of values for the field
 607      * then a {@code DateTimeException} will be thrown.
 608      * <p>
 609      * All other {@code ChronoField} instances will throw a {@code DateTimeException}.
 610      * <p>
 611      * If the field is not a {@code ChronoField}, then the result of this method
 612      * is obtained by invoking {@code TemporalField.adjustInto(Temporal, long)}
 613      * passing {@code this} as the argument. In this case, the field determines
 614      * whether and how to adjust the instant.
 615      * <p>
 616      * This instance is immutable and unaffected by this method call.
 617      *
 618      * @param field  the field to set in the result, not null
 619      * @param newValue  the new value of the field in the result
 620      * @return a {@code YearMonth} based on {@code this} with the specified field set, not null
 621      * @throws DateTimeException if the field cannot be set
 622      * @throws ArithmeticException if numeric overflow occurs
 623      */
 624     @Override
 625     public YearMonth with(TemporalField field, long newValue) {
 626         if (field instanceof ChronoField) {
 627             ChronoField f = (ChronoField) field;
 628             f.checkValidValue(newValue);
 629             switch (f) {
 630                 case MONTH_OF_YEAR: return withMonth((int) newValue);
 631                 case EPOCH_MONTH: return plusMonths(newValue - getLong(EPOCH_MONTH));
 632                 case YEAR_OF_ERA: return withYear((int) (year < 1 ? 1 - newValue : newValue));
 633                 case YEAR: return withYear((int) newValue);
 634                 case ERA: return (getLong(ERA) == newValue ? this : withYear(1 - year));
 635             }
 636             throw new DateTimeException("Unsupported field: " + field.getName());
 637         }
 638         return field.adjustInto(this, newValue);
 639     }
 640 
 641     //-----------------------------------------------------------------------
 642     /**
 643      * Returns a copy of this {@code YearMonth} with the year altered.
 644      * <p>
 645      * This instance is immutable and unaffected by this method call.
 646      *
 647      * @param year  the year to set in the returned year-month, from MIN_YEAR to MAX_YEAR
 648      * @return a {@code YearMonth} based on this year-month with the requested year, not null
 649      * @throws DateTimeException if the year value is invalid
 650      */
 651     public YearMonth withYear(int year) {
 652         YEAR.checkValidValue(year);
 653         return with(year, month);
 654     }
 655 
 656     /**
 657      * Returns a copy of this {@code YearMonth} with the month-of-year altered.
 658      * <p>
 659      * This instance is immutable and unaffected by this method call.
 660      *
 661      * @param month  the month-of-year to set in the returned year-month, from 1 (January) to 12 (December)
 662      * @return a {@code YearMonth} based on this year-month with the requested month, not null
 663      * @throws DateTimeException if the month-of-year value is invalid
 664      */
 665     public YearMonth withMonth(int month) {
 666         MONTH_OF_YEAR.checkValidValue(month);
 667         return with(year, month);
 668     }
 669 
 670     //-----------------------------------------------------------------------
 671     /**
 672      * Returns a copy of this year-month with the specified amount added.
 673      * <p>
 674      * This returns a {@code YearMonth}, based on this one, with the specified amount added.
 675      * The amount is typically {@link Period} but may be any other type implementing
 676      * the {@link TemporalAmount} interface.
 677      * <p>
 678      * The calculation is delegated to the amount object by calling
 679      * {@link TemporalAmount#addTo(Temporal)}. The amount implementation is free
 680      * to implement the addition in any way it wishes, however it typically
 681      * calls back to {@link #plus(long, TemporalUnit)}. Consult the documentation
 682      * of the amount implementation to determine if it can be successfully added.
 683      * <p>
 684      * This instance is immutable and unaffected by this method call.
 685      *
 686      * @param amountToAdd  the amount to add, not null
 687      * @return a {@code YearMonth} based on this year-month with the addition made, not null
 688      * @throws DateTimeException if the addition cannot be made
 689      * @throws ArithmeticException if numeric overflow occurs
 690      */
 691     @Override
 692     public YearMonth plus(TemporalAmount amountToAdd) {
 693         return (YearMonth) amountToAdd.addTo(this);
 694     }
 695 
 696     /**
 697      * Returns a copy of this year-month with the specified amount added.
 698      * <p>
 699      * This returns a {@code YearMonth}, based on this one, with the amount
 700      * in terms of the unit added. If it is not possible to add the amount, because the
 701      * unit is not supported or for some other reason, an exception is thrown.
 702      * <p>
 703      * If the field is a {@link ChronoUnit} then the addition is implemented here.
 704      * The supported fields behave as follows:
 705      * <ul>
 706      * <li>{@code MONTHS} -
 707      *  Returns a {@code YearMonth} with the specified number of months added.
 708      *  This is equivalent to {@link #plusMonths(long)}.
 709      * <li>{@code YEARS} -
 710      *  Returns a {@code YearMonth} with the specified number of years added.
 711      *  This is equivalent to {@link #plusYears(long)}.
 712      * <li>{@code DECADES} -
 713      *  Returns a {@code YearMonth} with the specified number of decades added.
 714      *  This is equivalent to calling {@link #plusYears(long)} with the amount
 715      *  multiplied by 10.
 716      * <li>{@code CENTURIES} -
 717      *  Returns a {@code YearMonth} with the specified number of centuries added.
 718      *  This is equivalent to calling {@link #plusYears(long)} with the amount
 719      *  multiplied by 100.
 720      * <li>{@code MILLENNIA} -
 721      *  Returns a {@code YearMonth} with the specified number of millennia added.
 722      *  This is equivalent to calling {@link #plusYears(long)} with the amount
 723      *  multiplied by 1,000.
 724      * <li>{@code ERAS} -
 725      *  Returns a {@code YearMonth} with the specified number of eras added.
 726      *  Only two eras are supported so the amount must be one, zero or minus one.
 727      *  If the amount is non-zero then the year is changed such that the year-of-era
 728      *  is unchanged.
 729      * </ul>
 730      * <p>
 731      * All other {@code ChronoUnit} instances will throw a {@code DateTimeException}.
 732      * <p>
 733      * If the field is not a {@code ChronoUnit}, then the result of this method
 734      * is obtained by invoking {@code TemporalUnit.addTo(Temporal, long)}
 735      * passing {@code this} as the argument. In this case, the unit determines
 736      * whether and how to perform the addition.
 737      * <p>
 738      * This instance is immutable and unaffected by this method call.
 739      *
 740      * @param amountToAdd  the amount of the unit to add to the result, may be negative
 741      * @param unit  the unit of the amount to add, not null
 742      * @return a {@code YearMonth} based on this year-month with the specified amount added, not null
 743      * @throws DateTimeException if the addition cannot be made
 744      * @throws ArithmeticException if numeric overflow occurs
 745      */
 746     @Override
 747     public YearMonth plus(long amountToAdd, TemporalUnit unit) {
 748         if (unit instanceof ChronoUnit) {
 749             switch ((ChronoUnit) unit) {
 750                 case MONTHS: return plusMonths(amountToAdd);
 751                 case YEARS: return plusYears(amountToAdd);
 752                 case DECADES: return plusYears(Math.multiplyExact(amountToAdd, 10));
 753                 case CENTURIES: return plusYears(Math.multiplyExact(amountToAdd, 100));
 754                 case MILLENNIA: return plusYears(Math.multiplyExact(amountToAdd, 1000));
 755                 case ERAS: return with(ERA, Math.addExact(getLong(ERA), amountToAdd));
 756             }
 757             throw new DateTimeException("Unsupported unit: " + unit.getName());
 758         }
 759         return unit.addTo(this, amountToAdd);
 760     }
 761 
 762     /**
 763      * Returns a copy of this year-month with the specified period in years added.
 764      * <p>
 765      * This instance is immutable and unaffected by this method call.
 766      *
 767      * @param yearsToAdd  the years to add, may be negative
 768      * @return a {@code YearMonth} based on this year-month with the years added, not null
 769      * @throws DateTimeException if the result exceeds the supported range
 770      */
 771     public YearMonth plusYears(long yearsToAdd) {
 772         if (yearsToAdd == 0) {
 773             return this;
 774         }
 775         int newYear = YEAR.checkValidIntValue(year + yearsToAdd);  // safe overflow
 776         return with(newYear, month);
 777     }
 778 
 779     /**


 781      * <p>
 782      * This instance is immutable and unaffected by this method call.
 783      *
 784      * @param monthsToAdd  the months to add, may be negative
 785      * @return a {@code YearMonth} based on this year-month with the months added, not null
 786      * @throws DateTimeException if the result exceeds the supported range
 787      */
 788     public YearMonth plusMonths(long monthsToAdd) {
 789         if (monthsToAdd == 0) {
 790             return this;
 791         }
 792         long monthCount = year * 12L + (month - 1);
 793         long calcMonths = monthCount + monthsToAdd;  // safe overflow
 794         int newYear = YEAR.checkValidIntValue(Math.floorDiv(calcMonths, 12));
 795         int newMonth = (int)Math.floorMod(calcMonths, 12) + 1;
 796         return with(newYear, newMonth);
 797     }
 798 
 799     //-----------------------------------------------------------------------
 800     /**
 801      * Returns a copy of this year-month with the specified amount subtracted.
 802      * <p>
 803      * This returns a {@code YearMonth}, based on this one, with the specified amount subtracted.
 804      * The amount is typically {@link Period} but may be any other type implementing
 805      * the {@link TemporalAmount} interface.
 806      * <p>
 807      * The calculation is delegated to the amount object by calling
 808      * {@link TemporalAmount#subtractFrom(Temporal)}. The amount implementation is free
 809      * to implement the subtraction in any way it wishes, however it typically
 810      * calls back to {@link #minus(long, TemporalUnit)}. Consult the documentation
 811      * of the amount implementation to determine if it can be successfully subtracted.
 812      * <p>
 813      * This instance is immutable and unaffected by this method call.
 814      *
 815      * @param amountToSubtract  the amount to subtract, not null
 816      * @return a {@code YearMonth} based on this year-month with the subtraction made, not null
 817      * @throws DateTimeException if the subtraction cannot be made
 818      * @throws ArithmeticException if numeric overflow occurs
 819      */
 820     @Override
 821     public YearMonth minus(TemporalAmount amountToSubtract) {
 822         return (YearMonth) amountToSubtract.subtractFrom(this);
 823     }
 824 
 825     /**
 826      * Returns a copy of this year-month with the specified amount subtracted.
 827      * <p>
 828      * This returns a {@code YearMonth}, based on this one, with the amount
 829      * in terms of the unit subtracted. If it is not possible to subtract the amount,
 830      * because the unit is not supported or for some other reason, an exception is thrown.
 831      * <p>
 832      * This method is equivalent to {@link #plus(long, TemporalUnit)} with the amount negated.
 833      * See that method for a full description of how addition, and thus subtraction, works.
 834      * <p>
 835      * This instance is immutable and unaffected by this method call.
 836      *
 837      * @param amountToSubtract  the amount of the unit to subtract from the result, may be negative
 838      * @param unit  the unit of the amount to subtract, not null
 839      * @return a {@code YearMonth} based on this year-month with the specified amount subtracted, not null
 840      * @throws DateTimeException if the subtraction cannot be made
 841      * @throws ArithmeticException if numeric overflow occurs
 842      */
 843     @Override
 844     public YearMonth minus(long amountToSubtract, TemporalUnit unit) {
 845         return (amountToSubtract == Long.MIN_VALUE ? plus(Long.MAX_VALUE, unit).plus(1, unit) : plus(-amountToSubtract, unit));
 846     }
 847 
 848     /**
 849      * Returns a copy of this year-month with the specified period in years subtracted.
 850      * <p>
 851      * This instance is immutable and unaffected by this method call.
 852      *
 853      * @param yearsToSubtract  the years to subtract, may be negative
 854      * @return a {@code YearMonth} based on this year-month with the years subtracted, not null
 855      * @throws DateTimeException if the result exceeds the supported range
 856      */
 857     public YearMonth minusYears(long yearsToSubtract) {
 858         return (yearsToSubtract == Long.MIN_VALUE ? plusYears(Long.MAX_VALUE).plusYears(1) : plusYears(-yearsToSubtract));
 859     }
 860 
 861     /**


 876      * Queries this year-month using the specified query.
 877      * <p>
 878      * This queries this year-month using the specified query strategy object.
 879      * The {@code TemporalQuery} object defines the logic to be used to
 880      * obtain the result. Read the documentation of the query to understand
 881      * what the result of this method will be.
 882      * <p>
 883      * The result of this method is obtained by invoking the
 884      * {@link TemporalQuery#queryFrom(TemporalAccessor)} method on the
 885      * specified query passing {@code this} as the argument.
 886      *
 887      * @param <R> the type of the result
 888      * @param query  the query to invoke, not null
 889      * @return the query result, null may be returned (defined by the query)
 890      * @throws DateTimeException if unable to query (defined by the query)
 891      * @throws ArithmeticException if numeric overflow occurs (defined by the query)
 892      */
 893     @SuppressWarnings("unchecked")
 894     @Override
 895     public <R> R query(TemporalQuery<R> query) {
 896         if (query == Queries.chronology()) {
 897             return (R) IsoChronology.INSTANCE;
 898         } else if (query == Queries.precision()) {
 899             return (R) MONTHS;
 900         }
 901         return Temporal.super.query(query);
 902     }
 903 
 904     /**
 905      * Adjusts the specified temporal object to have this year-month.
 906      * <p>
 907      * This returns a temporal object of the same observable type as the input
 908      * with the year and month changed to be the same as this.
 909      * <p>
 910      * The adjustment is equivalent to using {@link Temporal#with(TemporalField, long)}
 911      * passing {@link ChronoField#EPOCH_MONTH} as the field.
 912      * If the specified temporal object does not use the ISO calendar system then
 913      * a {@code DateTimeException} is thrown.
 914      * <p>
 915      * In most cases, it is clearer to reverse the calling pattern by using
 916      * {@link Temporal#with(TemporalAdjuster)}:
 917      * <pre>
 918      *   // these two lines are equivalent, but the second approach is recommended
 919      *   temporal = thisYearMonth.adjustInto(temporal);
 920      *   temporal = temporal.with(thisYearMonth);
 921      * </pre>
 922      * <p>
 923      * This instance is immutable and unaffected by this method call.
 924      *
 925      * @param temporal  the target object to be adjusted, not null
 926      * @return the adjusted object, not null
 927      * @throws DateTimeException if unable to make the adjustment
 928      * @throws ArithmeticException if numeric overflow occurs
 929      */
 930     @Override
 931     public Temporal adjustInto(Temporal temporal) {
 932         if (Chronology.from(temporal).equals(IsoChronology.INSTANCE) == false) {
 933             throw new DateTimeException("Adjustment only supported on ISO date-time");
 934         }
 935         return temporal.with(EPOCH_MONTH, getEpochMonth());
 936     }
 937 
 938     /**
 939      * Calculates the period between this year-month and another year-month in
 940      * terms of the specified unit.
 941      * <p>
 942      * This calculates the period between two year-months in terms of a single unit.
 943      * The start and end points are {@code this} and the specified year-month.
 944      * The result will be negative if the end is before the start.
 945      * The {@code Temporal} passed to this method must be a {@code YearMonth}.
 946      * For example, the period in years between two year-months can be calculated
 947      * using {@code startYearMonth.periodUntil(endYearMonth, YEARS)}.
 948      * <p>
 949      * The calculation returns a whole number, representing the number of
 950      * complete units between the two year-months.
 951      * For example, the period in decades between 2012-06 and 2032-05
 952      * will only be one decade as it is one month short of two decades.
 953      * <p>
 954      * There are two equivalent ways of using this method.
 955      * The first is to invoke this method.
 956      * The second is to use {@link TemporalUnit#between(Temporal, Temporal)}:

 957      * <pre>
 958      *   // these two lines are equivalent
 959      *   amount = start.periodUntil(end, MONTHS);
 960      *   amount = MONTHS.between(start, end);
 961      * </pre>
 962      * The choice should be made based on which makes the code more readable.
 963      * <p>
 964      * The calculation is implemented in this method for {@link ChronoUnit}.
 965      * The units {@code MONTHS}, {@code YEARS}, {@code DECADES},
 966      * {@code CENTURIES}, {@code MILLENNIA} and {@code ERAS} are supported.
 967      * Other {@code ChronoUnit} values will throw an exception.
 968      * <p>
 969      * If the unit is not a {@code ChronoUnit}, then the result of this method
 970      * is obtained by invoking {@code TemporalUnit.between(Temporal, Temporal)}
 971      * passing {@code this} as the first argument and the input temporal as
 972      * the second argument.
 973      * <p>
 974      * This instance is immutable and unaffected by this method call.
 975      *
 976      * @param endYearMonth  the end year-month, which must be a {@code YearMonth}, not null
 977      * @param unit  the unit to measure the period in, not null
 978      * @return the amount of the period between this year-month and the end year-month
 979      * @throws DateTimeException if the period cannot be calculated
 980      * @throws ArithmeticException if numeric overflow occurs
 981      */
 982     @Override
 983     public long periodUntil(Temporal endYearMonth, TemporalUnit unit) {
 984         if (endYearMonth instanceof YearMonth == false) {
 985             Objects.requireNonNull(endYearMonth, "endYearMonth");
 986             throw new DateTimeException("Unable to calculate period between objects of two different types");
 987         }
 988         YearMonth end = (YearMonth) endYearMonth;
 989         if (unit instanceof ChronoUnit) {
 990             long monthsUntil = end.getEpochMonth() - getEpochMonth();  // no overflow
 991             switch ((ChronoUnit) unit) {
 992                 case MONTHS: return monthsUntil;
 993                 case YEARS: return monthsUntil / 12;
 994                 case DECADES: return monthsUntil / 120;
 995                 case CENTURIES: return monthsUntil / 1200;
 996                 case MILLENNIA: return monthsUntil / 12000;
 997                 case ERAS: return end.getLong(ERA) - getLong(ERA);
 998             }
 999             throw new DateTimeException("Unsupported unit: " + unit.getName());
1000         }
1001         return unit.between(this, endYearMonth);
1002     }
1003 
1004     //-----------------------------------------------------------------------
1005     /**
1006      * Combines this year-month with a day-of-month to create a {@code LocalDate}.
1007      * <p>
1008      * This returns a {@code LocalDate} formed from this year-month and the specified day-of-month.
1009      * <p>

1010      * The day-of-month value must be valid for the year-month.
1011      * <p>
1012      * This method can be used as part of a chain to produce a date:
1013      * <pre>
1014      *  LocalDate date = year.atMonth(month).atDay(day);
1015      * </pre>


1016      *
1017      * @param dayOfMonth  the day-of-month to use, from 1 to 31
1018      * @return the date formed from this year-month and the specified day, not null
1019      * @throws DateTimeException if the day is invalid for the year-month
1020      * @see #isValidDay(int)
1021      */
1022     public LocalDate atDay(int dayOfMonth) {
1023         return LocalDate.of(year, month, dayOfMonth);
1024     }
1025 
1026     /**
1027      * Returns a {@code LocalDate} at the end of the month.
1028      * <p>
1029      * This returns a {@code LocalDate} based on this year-month.
1030      * The day-of-month is set to the last valid day of the month, taking
1031      * into account leap years.
1032      * <p>
1033      * This method can be used as part of a chain to produce a date:
1034      * <pre>
1035      *  LocalDate date = year.atMonth(month).atEndOfMonth();
1036      * </pre>
1037      *
1038      * @return the last valid date of this year-month, not null
1039      */
1040     public LocalDate atEndOfMonth() {
1041         return LocalDate.of(year, month, lengthOfMonth());
1042     }
1043 
1044     //-----------------------------------------------------------------------
1045     /**
1046      * Compares this year-month to another year-month.
1047      * <p>
1048      * The comparison is based first on the value of the year, then on the value of the month.
1049      * It is "consistent with equals", as defined by {@link Comparable}.
1050      *
1051      * @param other  the other year-month to compare to, not null
1052      * @return the comparator value, negative if less, positive if greater
1053      */
1054     @Override
1055     public int compareTo(YearMonth other) {
1056         int cmp = (year - other.year);
1057         if (cmp == 0) {
1058             cmp = (month - other.month);
1059         }
1060         return cmp;
1061     }
1062 
1063     /**


1124         int absYear = Math.abs(year);
1125         StringBuilder buf = new StringBuilder(9);
1126         if (absYear < 1000) {
1127             if (year < 0) {
1128                 buf.append(year - 10000).deleteCharAt(1);
1129             } else {
1130                 buf.append(year + 10000).deleteCharAt(0);
1131             }
1132         } else {
1133             buf.append(year);
1134         }
1135         return buf.append(month < 10 ? "-0" : "-")
1136             .append(month)
1137             .toString();
1138     }
1139 
1140     /**
1141      * Outputs this year-month as a {@code String} using the formatter.
1142      * <p>
1143      * This year-month will be passed to the formatter
1144      * {@link DateTimeFormatter#format(TemporalAccessor) format method}.
1145      *
1146      * @param formatter  the formatter to use, not null
1147      * @return the formatted year-month string, not null
1148      * @throws DateTimeException if an error occurs during printing
1149      */
1150     public String toString(DateTimeFormatter formatter) {
1151         Objects.requireNonNull(formatter, "formatter");
1152         return formatter.format(this);
1153     }
1154 
1155     //-----------------------------------------------------------------------
1156     /**
1157      * Writes the object using a
1158      * <a href="../../../serialized-form.html#java.time.temporal.Ser">dedicated serialized form</a>.
1159      * <pre>
1160      *  out.writeByte(12);  // identifies this as a YearMonth
1161      *  out.writeInt(year);
1162      *  out.writeByte(month);
1163      * </pre>
1164      *
1165      * @return the instance of {@code Ser}, not null
1166      */
1167     private Object writeReplace() {
1168         return new Ser(Ser.YEAR_MONTH_TYPE, this);
1169     }
1170 
1171     /**
1172      * Defend against malicious streams.
1173      * @return never
1174      * @throws InvalidObjectException always
1175      */
1176     private Object readResolve() throws ObjectStreamException {
1177         throw new InvalidObjectException("Deserialization via serialization delegate");
1178     }
1179 
1180     void writeExternal(DataOutput out) throws IOException {