1 /*
   2  * Copyright (c) 2012, 2023, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 /*
  27  * This file is available under and governed by the GNU General Public
  28  * License version 2 only, as published by the Free Software Foundation.
  29  * However, the following notice accompanied the original version of this
  30  * file:
  31  *
  32  * Copyright (c) 2007-2012, Stephen Colebourne & Michael Nascimento Santos
  33  *
  34  * All rights reserved.
  35  *
  36  * Redistribution and use in source and binary forms, with or without
  37  * modification, are permitted provided that the following conditions are met:
  38  *
  39  *  * Redistributions of source code must retain the above copyright notice,
  40  *    this list of conditions and the following disclaimer.
  41  *
  42  *  * Redistributions in binary form must reproduce the above copyright notice,
  43  *    this list of conditions and the following disclaimer in the documentation
  44  *    and/or other materials provided with the distribution.
  45  *
  46  *  * Neither the name of JSR-310 nor the names of its contributors
  47  *    may be used to endorse or promote products derived from this software
  48  *    without specific prior written permission.
  49  *
  50  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  51  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  52  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  53  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  54  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
  55  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  56  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  57  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  58  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  59  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  60  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  61  */
  62 package java.time;
  63 
  64 import static java.time.temporal.ChronoField.ERA;
  65 import static java.time.temporal.ChronoField.YEAR;
  66 import static java.time.temporal.ChronoField.YEAR_OF_ERA;
  67 import static java.time.temporal.ChronoUnit.CENTURIES;
  68 import static java.time.temporal.ChronoUnit.DECADES;
  69 import static java.time.temporal.ChronoUnit.ERAS;
  70 import static java.time.temporal.ChronoUnit.MILLENNIA;
  71 import static java.time.temporal.ChronoUnit.YEARS;
  72 
  73 import java.io.DataInput;
  74 import java.io.DataOutput;
  75 import java.io.IOException;
  76 import java.io.InvalidObjectException;
  77 import java.io.ObjectInputStream;
  78 import java.io.Serializable;
  79 import java.time.chrono.Chronology;
  80 import java.time.chrono.IsoChronology;
  81 import java.time.format.DateTimeFormatter;
  82 import java.time.format.DateTimeFormatterBuilder;
  83 import java.time.format.DateTimeParseException;
  84 import java.time.format.SignStyle;
  85 import java.time.temporal.ChronoField;
  86 import java.time.temporal.ChronoUnit;
  87 import java.time.temporal.Temporal;
  88 import java.time.temporal.TemporalAccessor;
  89 import java.time.temporal.TemporalAdjuster;
  90 import java.time.temporal.TemporalAmount;
  91 import java.time.temporal.TemporalField;
  92 import java.time.temporal.TemporalQueries;
  93 import java.time.temporal.TemporalQuery;
  94 import java.time.temporal.TemporalUnit;
  95 import java.time.temporal.UnsupportedTemporalTypeException;
  96 import java.time.temporal.ValueRange;
  97 import java.util.Objects;
  98 
  99 /**
 100  * A year in the ISO-8601 calendar system, such as {@code 2007}.
 101  * <p>
 102  * {@code Year} is an immutable date-time object that represents a year.
 103  * Any field that can be derived from a year can be obtained.
 104  * <p>
 105  * <b>Note that years in the ISO chronology only align with years in the
 106  * Gregorian-Julian system for modern years. Parts of Russia did not switch to the
 107  * modern Gregorian/ISO rules until 1920.
 108  * As such, historical years must be treated with caution.</b>
 109  * <p>
 110  * This class does not store or represent a month, day, time or time-zone.
 111  * For example, the value "2007" can be stored in a {@code Year}.
 112  * <p>
 113  * Years represented by this class follow the ISO-8601 standard and use
 114  * the proleptic numbering system. Year 1 is preceded by year 0, then by year -1.
 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 Year
 137         implements Temporal, TemporalAdjuster, Comparable<Year>, Serializable {
 138 
 139     /**
 140      * The minimum supported year, '-999,999,999'.
 141      */
 142     public static final int MIN_VALUE = -999_999_999;
 143     /**
 144      * The maximum supported year, '+999,999,999'.
 145      */
 146     public static final int MAX_VALUE = 999_999_999;
 147 
 148     /**
 149      * Serialization version.
 150      */
 151     @java.io.Serial
 152     private static final long serialVersionUID = -23038383694477807L;
 153     /**
 154      * Parser.
 155      */
 156     private static final DateTimeFormatter PARSER = new DateTimeFormatterBuilder()
 157         .parseLenient()
 158         .appendValue(YEAR, 1, 10, SignStyle.NORMAL)
 159         .toFormatter();
 160 
 161     /**
 162      * The year being represented.
 163      */
 164     private final int year;
 165 
 166     //-----------------------------------------------------------------------
 167     /**
 168      * Obtains the current year from the system clock in the default time-zone.
 169      * <p>
 170      * This will query the {@link Clock#systemDefaultZone() system clock} in the default
 171      * time-zone to obtain the current year.
 172      * <p>
 173      * Using this method will prevent the ability to use an alternate clock for testing
 174      * because the clock is hard-coded.
 175      *
 176      * @return the current year using the system clock and default time-zone, not null
 177      */
 178     public static Year now() {
 179         return now(Clock.systemDefaultZone());
 180     }
 181 
 182     /**
 183      * Obtains the current year from the system clock in the specified time-zone.
 184      * <p>
 185      * This will query the {@link Clock#system(ZoneId) system clock} to obtain the current year.
 186      * Specifying the time-zone avoids dependence on the default time-zone.
 187      * <p>
 188      * Using this method will prevent the ability to use an alternate clock for testing
 189      * because the clock is hard-coded.
 190      *
 191      * @param zone  the zone ID to use, not null
 192      * @return the current year using the system clock, not null
 193      */
 194     public static Year now(ZoneId zone) {
 195         return now(Clock.system(zone));
 196     }
 197 
 198     /**
 199      * Obtains the current year from the specified clock.
 200      * <p>
 201      * This will query the specified clock to obtain the current year.
 202      * Using this method allows the use of an alternate clock for testing.
 203      * The alternate clock may be introduced using {@link Clock dependency injection}.
 204      *
 205      * @param clock  the clock to use, not null
 206      * @return the current year, not null
 207      */
 208     public static Year now(Clock clock) {
 209         final LocalDate now = LocalDate.now(clock);  // called once
 210         return Year.of(now.getYear());
 211     }
 212 
 213     //-----------------------------------------------------------------------
 214     /**
 215      * Obtains an instance of {@code Year}.
 216      * <p>
 217      * This method accepts a year value from the proleptic ISO calendar system.
 218      * <p>
 219      * The year 2AD/CE is represented by 2.<br>
 220      * The year 1AD/CE is represented by 1.<br>
 221      * The year 1BC/BCE is represented by 0.<br>
 222      * The year 2BC/BCE is represented by -1.<br>
 223      *
 224      * @param isoYear  the ISO proleptic year to represent, from {@code MIN_VALUE} to {@code MAX_VALUE}
 225      * @return the year, not null
 226      * @throws DateTimeException if the field is invalid
 227      */
 228     public static Year of(int isoYear) {
 229         YEAR.checkValidValue(isoYear);
 230         return new Year(isoYear);
 231     }
 232 
 233     //-----------------------------------------------------------------------
 234     /**
 235      * Obtains an instance of {@code Year} from a temporal object.
 236      * <p>
 237      * This obtains a year based on the specified temporal.
 238      * A {@code TemporalAccessor} represents an arbitrary set of date and time information,
 239      * which this factory converts to an instance of {@code Year}.
 240      * <p>
 241      * The conversion extracts the {@link ChronoField#YEAR year} field.
 242      * The extraction is only permitted if the temporal object has an ISO
 243      * chronology, or can be converted to a {@code LocalDate}.
 244      * <p>
 245      * This method matches the signature of the functional interface {@link TemporalQuery}
 246      * allowing it to be used as a query via method reference, {@code Year::from}.
 247      *
 248      * @param temporal  the temporal object to convert, not null
 249      * @return the year, not null
 250      * @throws DateTimeException if unable to convert to a {@code Year}
 251      */
 252     public static Year from(TemporalAccessor temporal) {
 253         if (temporal instanceof Year) {
 254             return (Year) temporal;
 255         }
 256         Objects.requireNonNull(temporal, "temporal");
 257         try {
 258             if (IsoChronology.INSTANCE.equals(Chronology.from(temporal)) == false) {
 259                 temporal = LocalDate.from(temporal);
 260             }
 261             return of(temporal.get(YEAR));
 262         } catch (DateTimeException ex) {
 263             throw new DateTimeException("Unable to obtain Year from TemporalAccessor: " +
 264                     temporal + " of type " + temporal.getClass().getName(), ex);
 265         }
 266     }
 267 
 268     //-----------------------------------------------------------------------
 269     /**
 270      * Obtains an instance of {@code Year} from a text string such as {@code 2007}.
 271      * <p>
 272      * The string must represent a valid year.
 273      *
 274      * @param text  the text to parse such as "2007", not null
 275      * @return the parsed year, not null
 276      * @throws DateTimeParseException if the text cannot be parsed
 277      */
 278     public static Year parse(CharSequence text) {
 279         return parse(text, PARSER);
 280     }
 281 
 282     /**
 283      * Obtains an instance of {@code Year} from a text string using a specific formatter.
 284      * <p>
 285      * The text is parsed using the formatter, returning a year.
 286      *
 287      * @param text  the text to parse, not null
 288      * @param formatter  the formatter to use, not null
 289      * @return the parsed year, not null
 290      * @throws DateTimeParseException if the text cannot be parsed
 291      */
 292     public static Year parse(CharSequence text, DateTimeFormatter formatter) {
 293         Objects.requireNonNull(formatter, "formatter");
 294         return formatter.parse(text, Year::from);
 295     }
 296 
 297     //-------------------------------------------------------------------------
 298     /**
 299      * Checks if the year is a leap year, according to the ISO proleptic
 300      * calendar system rules.
 301      * <p>
 302      * This method applies the current rules for leap years across the whole time-line.
 303      * In general, a year is a leap year if it is divisible by four without
 304      * remainder. However, years divisible by 100, are not leap years, with
 305      * the exception of years divisible by 400 which are.
 306      * <p>
 307      * For example, 1904 is a leap year it is divisible by 4.
 308      * 1900 was not a leap year as it is divisible by 100, however 2000 was a
 309      * leap year as it is divisible by 400.
 310      * <p>
 311      * The calculation is proleptic - applying the same rules into the far future and far past.
 312      * This is historically inaccurate, but is correct for the ISO-8601 standard.
 313      *
 314      * @param year  the year to check
 315      * @return true if the year is leap, false otherwise
 316      */
 317     public static boolean isLeap(long year) {
 318         // A year that is a multiple of 100, 200 and 300 is not divisible by 16, but 400 is.
 319         // So for a year that's divisible by 4, checking that it's also divisible by 16
 320         // is sufficient to determine it must be a leap year.
 321         return (year & 15) == 0 ? (year & 3) == 0 : (year & 3) == 0 && year % 100 != 0;
 322     }
 323 
 324     //-----------------------------------------------------------------------
 325     /**
 326      * Constructor.
 327      *
 328      * @param year  the year to represent
 329      */
 330     private Year(int year) {
 331         this.year = year;
 332     }
 333 
 334     //-----------------------------------------------------------------------
 335     /**
 336      * Gets the year value.
 337      * <p>
 338      * The year returned by this method is proleptic as per {@code get(YEAR)}.
 339      *
 340      * @return the year, {@code MIN_VALUE} to {@code MAX_VALUE}
 341      */
 342     public int getValue() {
 343         return year;
 344     }
 345 
 346     //-----------------------------------------------------------------------
 347     /**
 348      * Checks if the specified field is supported.
 349      * <p>
 350      * This checks if this year can be queried for the specified field.
 351      * If false, then calling the {@link #range(TemporalField) range},
 352      * {@link #get(TemporalField) get} and {@link #with(TemporalField, long)}
 353      * methods will throw an exception.
 354      * <p>
 355      * If the field is a {@link ChronoField} then the query is implemented here.
 356      * The supported fields are:
 357      * <ul>
 358      * <li>{@code YEAR_OF_ERA}
 359      * <li>{@code YEAR}
 360      * <li>{@code ERA}
 361      * </ul>
 362      * All other {@code ChronoField} instances will return false.
 363      * <p>
 364      * If the field is not a {@code ChronoField}, then the result of this method
 365      * is obtained by invoking {@code TemporalField.isSupportedBy(TemporalAccessor)}
 366      * passing {@code this} as the argument.
 367      * Whether the field is supported is determined by the field.
 368      *
 369      * @param field  the field to check, null returns false
 370      * @return true if the field is supported on this year, false if not
 371      */
 372     @Override
 373     public boolean isSupported(TemporalField field) {
 374         if (field instanceof ChronoField) {
 375             return field == YEAR || field == YEAR_OF_ERA || field == ERA;
 376         }
 377         return field != null && field.isSupportedBy(this);
 378     }
 379 
 380     /**
 381      * Checks if the specified unit is supported.
 382      * <p>
 383      * This checks if the specified unit can be added to, or subtracted from, this year.
 384      * If false, then calling the {@link #plus(long, TemporalUnit)} and
 385      * {@link #minus(long, TemporalUnit) minus} methods will throw an exception.
 386      * <p>
 387      * If the unit is a {@link ChronoUnit} then the query is implemented here.
 388      * The supported units are:
 389      * <ul>
 390      * <li>{@code YEARS}
 391      * <li>{@code DECADES}
 392      * <li>{@code CENTURIES}
 393      * <li>{@code MILLENNIA}
 394      * <li>{@code ERAS}
 395      * </ul>
 396      * All other {@code ChronoUnit} instances will return false.
 397      * <p>
 398      * If the unit is not a {@code ChronoUnit}, then the result of this method
 399      * is obtained by invoking {@code TemporalUnit.isSupportedBy(Temporal)}
 400      * passing {@code this} as the argument.
 401      * Whether the unit is supported is determined by the unit.
 402      *
 403      * @param unit  the unit to check, null returns false
 404      * @return true if the unit can be added/subtracted, false if not
 405      */
 406     @Override
 407     public boolean isSupported(TemporalUnit unit) {
 408         if (unit instanceof ChronoUnit) {
 409             return unit == YEARS || unit == DECADES || unit == CENTURIES || unit == MILLENNIA || unit == ERAS;
 410         }
 411         return unit != null && unit.isSupportedBy(this);
 412     }
 413 
 414     //-----------------------------------------------------------------------
 415     /**
 416      * Gets the range of valid values for the specified field.
 417      * <p>
 418      * The range object expresses the minimum and maximum valid values for a field.
 419      * This year is used to enhance the accuracy of the returned range.
 420      * If it is not possible to return the range, because the field is not supported
 421      * or for some other reason, an exception is thrown.
 422      * <p>
 423      * If the field is a {@link ChronoField} then the query is implemented here.
 424      * The {@link #isSupported(TemporalField) supported fields} will return
 425      * appropriate range instances.
 426      * All other {@code ChronoField} instances will throw an {@code UnsupportedTemporalTypeException}.
 427      * <p>
 428      * If the field is not a {@code ChronoField}, then the result of this method
 429      * is obtained by invoking {@code TemporalField.rangeRefinedBy(TemporalAccessor)}
 430      * passing {@code this} as the argument.
 431      * Whether the range can be obtained is determined by the field.
 432      *
 433      * @param field  the field to query the range for, not null
 434      * @return the range of valid values for the field, not null
 435      * @throws DateTimeException if the range for the field cannot be obtained
 436      * @throws UnsupportedTemporalTypeException if the field is not supported
 437      */
 438     @Override
 439     public ValueRange range(TemporalField field) {
 440         if (field == YEAR_OF_ERA) {
 441             return (year <= 0 ? ValueRange.of(1, MAX_VALUE + 1) : ValueRange.of(1, MAX_VALUE));
 442         }
 443         return Temporal.super.range(field);
 444     }
 445 
 446     /**
 447      * Gets the value of the specified field from this year as an {@code int}.
 448      * <p>
 449      * This queries this year for the value of the specified field.
 450      * The returned value will always be within the valid range of values for the field.
 451      * If it is not possible to return the value, because the field is not supported
 452      * or for some other reason, an exception is thrown.
 453      * <p>
 454      * If the field is a {@link ChronoField} then the query is implemented here.
 455      * The {@link #isSupported(TemporalField) supported fields} will return valid
 456      * values based on this year.
 457      * All other {@code ChronoField} instances will throw an {@code UnsupportedTemporalTypeException}.
 458      * <p>
 459      * If the field is not a {@code ChronoField}, then the result of this method
 460      * is obtained by invoking {@code TemporalField.getFrom(TemporalAccessor)}
 461      * passing {@code this} as the argument. Whether the value can be obtained,
 462      * and what the value represents, is determined by the field.
 463      *
 464      * @param field  the field to get, not null
 465      * @return the value for the field
 466      * @throws DateTimeException if a value for the field cannot be obtained or
 467      *         the value is outside the range of valid values for the field
 468      * @throws UnsupportedTemporalTypeException if the field is not supported or
 469      *         the range of values exceeds an {@code int}
 470      * @throws ArithmeticException if numeric overflow occurs
 471      */
 472     @Override  // override for Javadoc
 473     public int get(TemporalField field) {
 474         return range(field).checkValidIntValue(getLong(field), field);
 475     }
 476 
 477     /**
 478      * Gets the value of the specified field from this year as a {@code long}.
 479      * <p>
 480      * This queries this year for the value of the specified field.
 481      * If it is not possible to return the value, because the field is not supported
 482      * or for some other reason, an exception is thrown.
 483      * <p>
 484      * If the field is a {@link ChronoField} then the query is implemented here.
 485      * The {@link #isSupported(TemporalField) supported fields} will return valid
 486      * values based on this year.
 487      * All other {@code ChronoField} instances will throw an {@code UnsupportedTemporalTypeException}.
 488      * <p>
 489      * If the field is not a {@code ChronoField}, then the result of this method
 490      * is obtained by invoking {@code TemporalField.getFrom(TemporalAccessor)}
 491      * passing {@code this} as the argument. Whether the value can be obtained,
 492      * and what the value represents, is determined by the field.
 493      *
 494      * @param field  the field to get, not null
 495      * @return the value for the field
 496      * @throws DateTimeException if a value for the field cannot be obtained
 497      * @throws UnsupportedTemporalTypeException if the field is not supported
 498      * @throws ArithmeticException if numeric overflow occurs
 499      */
 500     @Override
 501     public long getLong(TemporalField field) {
 502         if (field instanceof ChronoField chronoField) {
 503             return switch (chronoField) {
 504                 case YEAR_OF_ERA -> year < 1 ? 1 - year : year;
 505                 case YEAR -> year;
 506                 case ERA -> year < 1 ? 0 : 1;
 507                 default -> throw new UnsupportedTemporalTypeException("Unsupported field: " + field);
 508             };
 509         }
 510         return field.getFrom(this);
 511     }
 512 
 513     //-----------------------------------------------------------------------
 514     /**
 515      * Checks if the year is a leap year, according to the ISO proleptic
 516      * calendar system rules.
 517      * <p>
 518      * This method applies the current rules for leap years across the whole time-line.
 519      * In general, a year is a leap year if it is divisible by four without
 520      * remainder. However, years divisible by 100, are not leap years, with
 521      * the exception of years divisible by 400 which are.
 522      * <p>
 523      * For example, 1904 is a leap year it is divisible by 4.
 524      * 1900 was not a leap year as it is divisible by 100, however 2000 was a
 525      * leap year as it is divisible by 400.
 526      * <p>
 527      * The calculation is proleptic - applying the same rules into the far future and far past.
 528      * This is historically inaccurate, but is correct for the ISO-8601 standard.
 529      *
 530      * @return true if the year is leap, false otherwise
 531      */
 532     public boolean isLeap() {
 533         return Year.isLeap(year);
 534     }
 535 
 536     /**
 537      * Checks if the month-day is valid for this year.
 538      * <p>
 539      * This method checks whether this year and the input month and day form
 540      * a valid date.
 541      *
 542      * @param monthDay  the month-day to validate, null returns false
 543      * @return true if the month and day are valid for this year
 544      */
 545     public boolean isValidMonthDay(MonthDay monthDay) {
 546         return monthDay != null && monthDay.isValidYear(year);
 547     }
 548 
 549     /**
 550      * Gets the length of this year in days.
 551      *
 552      * @return the length of this year in days, 365 or 366
 553      */
 554     public int length() {
 555         return isLeap() ? 366 : 365;
 556     }
 557 
 558     //-----------------------------------------------------------------------
 559     /**
 560      * Returns an adjusted copy of this year.
 561      * <p>
 562      * This returns a {@code Year}, based on this one, with the year adjusted.
 563      * The adjustment takes place using the specified adjuster strategy object.
 564      * Read the documentation of the adjuster to understand what adjustment will be made.
 565      * <p>
 566      * The result of this method is obtained by invoking the
 567      * {@link TemporalAdjuster#adjustInto(Temporal)} method on the
 568      * specified adjuster passing {@code this} as the argument.
 569      * <p>
 570      * This instance is immutable and unaffected by this method call.
 571      *
 572      * @param adjuster the adjuster to use, not null
 573      * @return a {@code Year} based on {@code this} with the adjustment made, not null
 574      * @throws DateTimeException if the adjustment cannot be made
 575      * @throws ArithmeticException if numeric overflow occurs
 576      */
 577     @Override
 578     public Year with(TemporalAdjuster adjuster) {
 579         return (Year) adjuster.adjustInto(this);
 580     }
 581 
 582     /**
 583      * Returns a copy of this year with the specified field set to a new value.
 584      * <p>
 585      * This returns a {@code Year}, based on this one, with the value
 586      * for the specified field changed.
 587      * If it is not possible to set the value, because the field is not supported or for
 588      * some other reason, an exception is thrown.
 589      * <p>
 590      * If the field is a {@link ChronoField} then the adjustment is implemented here.
 591      * The supported fields behave as follows:
 592      * <ul>
 593      * <li>{@code YEAR_OF_ERA} -
 594      *  Returns a {@code Year} with the specified year-of-era
 595      *  The era will be unchanged.
 596      * <li>{@code YEAR} -
 597      *  Returns a {@code Year} with the specified year.
 598      *  This completely replaces the date and is equivalent to {@link #of(int)}.
 599      * <li>{@code ERA} -
 600      *  Returns a {@code Year} with the specified era.
 601      *  The year-of-era will be unchanged.
 602      * </ul>
 603      * <p>
 604      * In all cases, if the new value is outside the valid range of values for the field
 605      * then a {@code DateTimeException} will be thrown.
 606      * <p>
 607      * All other {@code ChronoField} instances will throw an {@code UnsupportedTemporalTypeException}.
 608      * <p>
 609      * If the field is not a {@code ChronoField}, then the result of this method
 610      * is obtained by invoking {@code TemporalField.adjustInto(Temporal, long)}
 611      * passing {@code this} as the argument. In this case, the field determines
 612      * whether and how to adjust the instant.
 613      * <p>
 614      * This instance is immutable and unaffected by this method call.
 615      *
 616      * @param field  the field to set in the result, not null
 617      * @param newValue  the new value of the field in the result
 618      * @return a {@code Year} based on {@code this} with the specified field set, not null
 619      * @throws DateTimeException if the field cannot be set
 620      * @throws UnsupportedTemporalTypeException if the field is not supported
 621      * @throws ArithmeticException if numeric overflow occurs
 622      */
 623     @Override
 624     public Year with(TemporalField field, long newValue) {
 625         if (field instanceof ChronoField chronoField) {
 626             chronoField.checkValidValue(newValue);
 627             return switch (chronoField) {
 628                 case YEAR_OF_ERA -> Year.of((int) (year < 1 ? 1 - newValue : newValue));
 629                 case YEAR -> Year.of((int) newValue);
 630                 case ERA -> getLong(ERA) == newValue ? this : Year.of(1 - year);
 631                 default -> throw new UnsupportedTemporalTypeException("Unsupported field: " + field);
 632             };
 633         }
 634         return field.adjustInto(this, newValue);
 635     }
 636 
 637     //-----------------------------------------------------------------------
 638     /**
 639      * Returns a copy of this year with the specified amount added.
 640      * <p>
 641      * This returns a {@code Year}, based on this one, with the specified amount added.
 642      * The amount is typically {@link Period} but may be any other type implementing
 643      * the {@link TemporalAmount} interface.
 644      * <p>
 645      * The calculation is delegated to the amount object by calling
 646      * {@link TemporalAmount#addTo(Temporal)}. The amount implementation is free
 647      * to implement the addition in any way it wishes, however it typically
 648      * calls back to {@link #plus(long, TemporalUnit)}. Consult the documentation
 649      * of the amount implementation to determine if it can be successfully added.
 650      * <p>
 651      * This instance is immutable and unaffected by this method call.
 652      *
 653      * @param amountToAdd  the amount to add, not null
 654      * @return a {@code Year} based on this year with the addition made, not null
 655      * @throws DateTimeException if the addition cannot be made
 656      * @throws ArithmeticException if numeric overflow occurs
 657      */
 658     @Override
 659     public Year plus(TemporalAmount amountToAdd) {
 660         return (Year) amountToAdd.addTo(this);
 661     }
 662 
 663     /**
 664      * Returns a copy of this year with the specified amount added.
 665      * <p>
 666      * This returns a {@code Year}, based on this one, with the amount
 667      * in terms of the unit added. If it is not possible to add the amount, because the
 668      * unit is not supported or for some other reason, an exception is thrown.
 669      * <p>
 670      * If the field is a {@link ChronoUnit} then the addition is implemented here.
 671      * The supported fields behave as follows:
 672      * <ul>
 673      * <li>{@code YEARS} -
 674      *  Returns a {@code Year} with the specified number of years added.
 675      *  This is equivalent to {@link #plusYears(long)}.
 676      * <li>{@code DECADES} -
 677      *  Returns a {@code Year} with the specified number of decades added.
 678      *  This is equivalent to calling {@link #plusYears(long)} with the amount
 679      *  multiplied by 10.
 680      * <li>{@code CENTURIES} -
 681      *  Returns a {@code Year} with the specified number of centuries added.
 682      *  This is equivalent to calling {@link #plusYears(long)} with the amount
 683      *  multiplied by 100.
 684      * <li>{@code MILLENNIA} -
 685      *  Returns a {@code Year} with the specified number of millennia added.
 686      *  This is equivalent to calling {@link #plusYears(long)} with the amount
 687      *  multiplied by 1,000.
 688      * <li>{@code ERAS} -
 689      *  Returns a {@code Year} with the specified number of eras added.
 690      *  Only two eras are supported so the amount must be one, zero or minus one.
 691      *  If the amount is non-zero then the year is changed such that the year-of-era
 692      *  is unchanged.
 693      * </ul>
 694      * <p>
 695      * All other {@code ChronoUnit} instances will throw an {@code UnsupportedTemporalTypeException}.
 696      * <p>
 697      * If the field is not a {@code ChronoUnit}, then the result of this method
 698      * is obtained by invoking {@code TemporalUnit.addTo(Temporal, long)}
 699      * passing {@code this} as the argument. In this case, the unit determines
 700      * whether and how to perform the addition.
 701      * <p>
 702      * This instance is immutable and unaffected by this method call.
 703      *
 704      * @param amountToAdd  the amount of the unit to add to the result, may be negative
 705      * @param unit  the unit of the amount to add, not null
 706      * @return a {@code Year} based on this year with the specified amount added, not null
 707      * @throws DateTimeException if the addition cannot be made
 708      * @throws UnsupportedTemporalTypeException if the unit is not supported
 709      * @throws ArithmeticException if numeric overflow occurs
 710      */
 711     @Override
 712     public Year plus(long amountToAdd, TemporalUnit unit) {
 713         if (unit instanceof ChronoUnit chronoUnit) {
 714             return switch (chronoUnit) {
 715                 case YEARS     -> plusYears(amountToAdd);
 716                 case DECADES   -> plusYears(Math.multiplyExact(amountToAdd, 10));
 717                 case CENTURIES -> plusYears(Math.multiplyExact(amountToAdd, 100));
 718                 case MILLENNIA -> plusYears(Math.multiplyExact(amountToAdd, 1000));
 719                 case ERAS      -> with(ERA, Math.addExact(getLong(ERA), amountToAdd));
 720                 default -> throw new UnsupportedTemporalTypeException("Unsupported unit: " + unit);
 721             };
 722         }
 723         return unit.addTo(this, amountToAdd);
 724     }
 725 
 726     /**
 727      * Returns a copy of this {@code Year} with the specified number of years added.
 728      * <p>
 729      * This instance is immutable and unaffected by this method call.
 730      *
 731      * @param yearsToAdd  the years to add, may be negative
 732      * @return a {@code Year} based on this year with the years added, not null
 733      * @throws DateTimeException if the result exceeds the supported range
 734      */
 735     public Year plusYears(long yearsToAdd) {
 736         if (yearsToAdd == 0) {
 737             return this;
 738         }
 739         return of(YEAR.checkValidIntValue(year + yearsToAdd));  // overflow safe
 740     }
 741 
 742     //-----------------------------------------------------------------------
 743     /**
 744      * Returns a copy of this year with the specified amount subtracted.
 745      * <p>
 746      * This returns a {@code Year}, based on this one, with the specified amount subtracted.
 747      * The amount is typically {@link Period} but may be any other type implementing
 748      * the {@link TemporalAmount} interface.
 749      * <p>
 750      * The calculation is delegated to the amount object by calling
 751      * {@link TemporalAmount#subtractFrom(Temporal)}. The amount implementation is free
 752      * to implement the subtraction in any way it wishes, however it typically
 753      * calls back to {@link #minus(long, TemporalUnit)}. Consult the documentation
 754      * of the amount implementation to determine if it can be successfully subtracted.
 755      * <p>
 756      * This instance is immutable and unaffected by this method call.
 757      *
 758      * @param amountToSubtract  the amount to subtract, not null
 759      * @return a {@code Year} based on this year with the subtraction made, not null
 760      * @throws DateTimeException if the subtraction cannot be made
 761      * @throws ArithmeticException if numeric overflow occurs
 762      */
 763     @Override
 764     public Year minus(TemporalAmount amountToSubtract) {
 765         return (Year) amountToSubtract.subtractFrom(this);
 766     }
 767 
 768     /**
 769      * Returns a copy of this year with the specified amount subtracted.
 770      * <p>
 771      * This returns a {@code Year}, based on this one, with the amount
 772      * in terms of the unit subtracted. If it is not possible to subtract the amount,
 773      * because the unit is not supported or for some other reason, an exception is thrown.
 774      * <p>
 775      * This method is equivalent to {@link #plus(long, TemporalUnit)} with the amount negated.
 776      * See that method for a full description of how addition, and thus subtraction, works.
 777      * <p>
 778      * This instance is immutable and unaffected by this method call.
 779      *
 780      * @param amountToSubtract  the amount of the unit to subtract from the result, may be negative
 781      * @param unit  the unit of the amount to subtract, not null
 782      * @return a {@code Year} based on this year with the specified amount subtracted, not null
 783      * @throws DateTimeException if the subtraction cannot be made
 784      * @throws UnsupportedTemporalTypeException if the unit is not supported
 785      * @throws ArithmeticException if numeric overflow occurs
 786      */
 787     @Override
 788     public Year minus(long amountToSubtract, TemporalUnit unit) {
 789         return (amountToSubtract == Long.MIN_VALUE ? plus(Long.MAX_VALUE, unit).plus(1, unit) : plus(-amountToSubtract, unit));
 790     }
 791 
 792     /**
 793      * Returns a copy of this {@code Year} with the specified number of years subtracted.
 794      * <p>
 795      * This instance is immutable and unaffected by this method call.
 796      *
 797      * @param yearsToSubtract  the years to subtract, may be negative
 798      * @return a {@code Year} based on this year with the year subtracted, not null
 799      * @throws DateTimeException if the result exceeds the supported range
 800      */
 801     public Year minusYears(long yearsToSubtract) {
 802         return (yearsToSubtract == Long.MIN_VALUE ? plusYears(Long.MAX_VALUE).plusYears(1) : plusYears(-yearsToSubtract));
 803     }
 804 
 805     //-----------------------------------------------------------------------
 806     /**
 807      * Queries this year using the specified query.
 808      * <p>
 809      * This queries this year using the specified query strategy object.
 810      * The {@code TemporalQuery} object defines the logic to be used to
 811      * obtain the result. Read the documentation of the query to understand
 812      * what the result of this method will be.
 813      * <p>
 814      * The result of this method is obtained by invoking the
 815      * {@link TemporalQuery#queryFrom(TemporalAccessor)} method on the
 816      * specified query passing {@code this} as the argument.
 817      *
 818      * @param <R> the type of the result
 819      * @param query  the query to invoke, not null
 820      * @return the query result, null may be returned (defined by the query)
 821      * @throws DateTimeException if unable to query (defined by the query)
 822      * @throws ArithmeticException if numeric overflow occurs (defined by the query)
 823      */
 824     @SuppressWarnings("unchecked")
 825     @Override
 826     public <R> R query(TemporalQuery<R> query) {
 827         if (query == TemporalQueries.chronology()) {
 828             return (R) IsoChronology.INSTANCE;
 829         } else if (query == TemporalQueries.precision()) {
 830             return (R) YEARS;
 831         }
 832         return Temporal.super.query(query);
 833     }
 834 
 835     /**
 836      * Adjusts the specified temporal object to have this year.
 837      * <p>
 838      * This returns a temporal object of the same observable type as the input
 839      * with the year changed to be the same as this.
 840      * <p>
 841      * The adjustment is equivalent to using {@link Temporal#with(TemporalField, long)}
 842      * passing {@link ChronoField#YEAR} as the field.
 843      * If the specified temporal object does not use the ISO calendar system then
 844      * a {@code DateTimeException} is thrown.
 845      * <p>
 846      * In most cases, it is clearer to reverse the calling pattern by using
 847      * {@link Temporal#with(TemporalAdjuster)}:
 848      * <pre>
 849      *   // these two lines are equivalent, but the second approach is recommended
 850      *   temporal = thisYear.adjustInto(temporal);
 851      *   temporal = temporal.with(thisYear);
 852      * </pre>
 853      * <p>
 854      * This instance is immutable and unaffected by this method call.
 855      *
 856      * @param temporal  the target object to be adjusted, not null
 857      * @return the adjusted object, not null
 858      * @throws DateTimeException if unable to make the adjustment
 859      * @throws ArithmeticException if numeric overflow occurs
 860      */
 861     @Override
 862     public Temporal adjustInto(Temporal temporal) {
 863         if (Chronology.from(temporal).equals(IsoChronology.INSTANCE) == false) {
 864             throw new DateTimeException("Adjustment only supported on ISO date-time");
 865         }
 866         return temporal.with(YEAR, year);
 867     }
 868 
 869     /**
 870      * Calculates the amount of time until another year in terms of the specified unit.
 871      * <p>
 872      * This calculates the amount of time between two {@code Year}
 873      * objects in terms of a single {@code TemporalUnit}.
 874      * The start and end points are {@code this} and the specified year.
 875      * The result will be negative if the end is before the start.
 876      * The {@code Temporal} passed to this method is converted to a
 877      * {@code Year} using {@link #from(TemporalAccessor)}.
 878      * For example, the amount in decades between two year can be calculated
 879      * using {@code startYear.until(endYear, DECADES)}.
 880      * <p>
 881      * The calculation returns a whole number, representing the number of
 882      * complete units between the two years.
 883      * For example, the amount in decades between 2012 and 2031
 884      * will only be one decade as it is one year short of two decades.
 885      * <p>
 886      * There are two equivalent ways of using this method.
 887      * The first is to invoke this method.
 888      * The second is to use {@link TemporalUnit#between(Temporal, Temporal)}:
 889      * <pre>
 890      *   // these two lines are equivalent
 891      *   amount = start.until(end, YEARS);
 892      *   amount = YEARS.between(start, end);
 893      * </pre>
 894      * The choice should be made based on which makes the code more readable.
 895      * <p>
 896      * The calculation is implemented in this method for {@link ChronoUnit}.
 897      * The units {@code YEARS}, {@code DECADES}, {@code CENTURIES},
 898      * {@code MILLENNIA} and {@code ERAS} are supported.
 899      * Other {@code ChronoUnit} values will throw an exception.
 900      * <p>
 901      * If the unit is not a {@code ChronoUnit}, then the result of this method
 902      * is obtained by invoking {@code TemporalUnit.between(Temporal, Temporal)}
 903      * passing {@code this} as the first argument and the converted input temporal
 904      * as the second argument.
 905      * <p>
 906      * This instance is immutable and unaffected by this method call.
 907      *
 908      * @param endExclusive  the end date, exclusive, which is converted to a {@code Year}, not null
 909      * @param unit  the unit to measure the amount in, not null
 910      * @return the amount of time between this year and the end year
 911      * @throws DateTimeException if the amount cannot be calculated, or the end
 912      *  temporal cannot be converted to a {@code Year}
 913      * @throws UnsupportedTemporalTypeException if the unit is not supported
 914      * @throws ArithmeticException if numeric overflow occurs
 915      */
 916     @Override
 917     public long until(Temporal endExclusive, TemporalUnit unit) {
 918         Year end = Year.from(endExclusive);
 919         if (unit instanceof ChronoUnit chronoUnit) {
 920             long yearsUntil = ((long) end.year) - year;  // no overflow
 921             return switch (chronoUnit) {
 922                 case YEARS     -> yearsUntil;
 923                 case DECADES   -> yearsUntil / 10;
 924                 case CENTURIES -> yearsUntil / 100;
 925                 case MILLENNIA -> yearsUntil / 1000;
 926                 case ERAS      -> end.getLong(ERA) - getLong(ERA);
 927                 default -> throw new UnsupportedTemporalTypeException("Unsupported unit: " + unit);
 928             };
 929         }
 930         return unit.between(this, end);
 931     }
 932 
 933     /**
 934      * Formats this year using the specified formatter.
 935      * <p>
 936      * This year will be passed to the formatter to produce a string.
 937      *
 938      * @param formatter  the formatter to use, not null
 939      * @return the formatted year string, not null
 940      * @throws DateTimeException if an error occurs during printing
 941      */
 942     public String format(DateTimeFormatter formatter) {
 943         Objects.requireNonNull(formatter, "formatter");
 944         return formatter.format(this);
 945     }
 946 
 947     //-----------------------------------------------------------------------
 948     /**
 949      * Combines this year with a day-of-year to create a {@code LocalDate}.
 950      * <p>
 951      * This returns a {@code LocalDate} formed from this year and the specified day-of-year.
 952      * <p>
 953      * The day-of-year value 366 is only valid in a leap year.
 954      *
 955      * @param dayOfYear  the day-of-year to use, from 1 to 365-366
 956      * @return the local date formed from this year and the specified date of year, not null
 957      * @throws DateTimeException if the day of year is zero or less, 366 or greater or equal
 958      *  to 366 and this is not a leap year
 959      */
 960     public LocalDate atDay(int dayOfYear) {
 961         return LocalDate.ofYearDay(year, dayOfYear);
 962     }
 963 
 964     /**
 965      * Combines this year with a month to create a {@code YearMonth}.
 966      * <p>
 967      * This returns a {@code YearMonth} formed from this year and the specified month.
 968      * All possible combinations of year and month are valid.
 969      * <p>
 970      * This method can be used as part of a chain to produce a date:
 971      * <pre>
 972      *  LocalDate date = year.atMonth(month).atDay(day);
 973      * </pre>
 974      *
 975      * @param month  the month-of-year to use, not null
 976      * @return the year-month formed from this year and the specified month, not null
 977      */
 978     public YearMonth atMonth(Month month) {
 979         return YearMonth.of(year, month);
 980     }
 981 
 982     /**
 983      * Combines this year with a month to create a {@code YearMonth}.
 984      * <p>
 985      * This returns a {@code YearMonth} formed from this year and the specified month.
 986      * All possible combinations of year and month are valid.
 987      * <p>
 988      * This method can be used as part of a chain to produce a date:
 989      * <pre>
 990      *  LocalDate date = year.atMonth(month).atDay(day);
 991      * </pre>
 992      *
 993      * @param month  the month-of-year to use, from 1 (January) to 12 (December)
 994      * @return the year-month formed from this year and the specified month, not null
 995      * @throws DateTimeException if the month is invalid
 996      */
 997     public YearMonth atMonth(int month) {
 998         return YearMonth.of(year, month);
 999     }
1000 
1001     /**
1002      * Combines this year with a month-day to create a {@code LocalDate}.
1003      * <p>
1004      * This returns a {@code LocalDate} formed from this year and the specified month-day.
1005      * <p>
1006      * A month-day of February 29th will be adjusted to February 28th in the resulting
1007      * date if the year is not a leap year.
1008      *
1009      * @param monthDay  the month-day to use, not null
1010      * @return the local date formed from this year and the specified month-day, not null
1011      */
1012     public LocalDate atMonthDay(MonthDay monthDay) {
1013         return monthDay.atYear(year);
1014     }
1015 
1016     //-----------------------------------------------------------------------
1017     /**
1018      * Compares this year to another year.
1019      * <p>
1020      * The comparison is based on the value of the year.
1021      * It is "consistent with equals", as defined by {@link Comparable}.
1022      *
1023      * @param other  the other year to compare to, not null
1024      * @return the comparator value, that is less than zero if this is before {@code other},
1025      *          zero if they are equal, or greater than zero if this is after {@code other}
1026      * @see #isBefore
1027      * @see #isAfter
1028      */
1029     @Override
1030     public int compareTo(Year other) {
1031         return year - other.year;
1032     }
1033 
1034     /**
1035      * Checks if this year is after the specified year.
1036      *
1037      * @param other  the other year to compare to, not null
1038      * @return true if this is after the specified year
1039      */
1040     public boolean isAfter(Year other) {
1041         return year > other.year;
1042     }
1043 
1044     /**
1045      * Checks if this year is before the specified year.
1046      *
1047      * @param other  the other year to compare to, not null
1048      * @return true if this point is before the specified year
1049      */
1050     public boolean isBefore(Year other) {
1051         return year < other.year;
1052     }
1053 
1054     //-----------------------------------------------------------------------
1055     /**
1056      * Checks if this year is equal to another year.
1057      * <p>
1058      * The comparison is based on the time-line position of the years.
1059      *
1060      * @param obj  the object to check, null returns false
1061      * @return true if this is equal to the other year
1062      */
1063     @Override
1064     public boolean equals(Object obj) {
1065         if (this == obj) {
1066             return true;
1067         }
1068         if (obj instanceof Year) {
1069             return year == ((Year) obj).year;
1070         }
1071         return false;
1072     }
1073 
1074     /**
1075      * A hash code for this year.
1076      *
1077      * @return a suitable hash code
1078      */
1079     @Override
1080     public int hashCode() {
1081         return year;
1082     }
1083 
1084     //-----------------------------------------------------------------------
1085     /**
1086      * Outputs this year as a {@code String}.
1087      *
1088      * @return a string representation of this year, not null
1089      */
1090     @Override
1091     public String toString() {
1092         return Integer.toString(year);
1093     }
1094 
1095     //-----------------------------------------------------------------------
1096     /**
1097      * Writes the object using a
1098      * <a href="{@docRoot}/serialized-form.html#java.time.Ser">dedicated serialized form</a>.
1099      * @serialData
1100      * <pre>
1101      *  out.writeByte(11);  // identifies a Year
1102      *  out.writeInt(year);
1103      * </pre>
1104      *
1105      * @return the instance of {@code Ser}, not null
1106      */
1107     @java.io.Serial
1108     private Object writeReplace() {
1109         return new Ser(Ser.YEAR_TYPE, this);
1110     }
1111 
1112     /**
1113      * Defend against malicious streams.
1114      *
1115      * @param s the stream to read
1116      * @throws InvalidObjectException always
1117      */
1118     @java.io.Serial
1119     private void readObject(ObjectInputStream s) throws InvalidObjectException {
1120         throw new InvalidObjectException("Deserialization via serialization delegate");
1121     }
1122 
1123     void writeExternal(DataOutput out) throws IOException {
1124         out.writeInt(year);
1125     }
1126 
1127     static Year readExternal(DataInput in) throws IOException {
1128         return Year.of(in.readInt());
1129     }
1130 
1131 }