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