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