Path: blob/aarch64-shenandoah-jdk8u272-b10/jdk/src/share/classes/java/time/Year.java
38829 views
/*1* Copyright (c) 2012, 2015, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/2425/*26* This file is available under and governed by the GNU General Public27* License version 2 only, as published by the Free Software Foundation.28* However, the following notice accompanied the original version of this29* file:30*31* Copyright (c) 2007-2012, Stephen Colebourne & Michael Nascimento Santos32*33* All rights reserved.34*35* Redistribution and use in source and binary forms, with or without36* modification, are permitted provided that the following conditions are met:37*38* * Redistributions of source code must retain the above copyright notice,39* this list of conditions and the following disclaimer.40*41* * Redistributions in binary form must reproduce the above copyright notice,42* this list of conditions and the following disclaimer in the documentation43* and/or other materials provided with the distribution.44*45* * Neither the name of JSR-310 nor the names of its contributors46* may be used to endorse or promote products derived from this software47* without specific prior written permission.48*49* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS50* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT51* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR52* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR53* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,54* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,55* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR56* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF57* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING58* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS59* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.60*/61package java.time;6263import static java.time.temporal.ChronoField.ERA;64import static java.time.temporal.ChronoField.YEAR;65import static java.time.temporal.ChronoField.YEAR_OF_ERA;66import static java.time.temporal.ChronoUnit.CENTURIES;67import static java.time.temporal.ChronoUnit.DECADES;68import static java.time.temporal.ChronoUnit.ERAS;69import static java.time.temporal.ChronoUnit.MILLENNIA;70import static java.time.temporal.ChronoUnit.YEARS;7172import java.io.DataInput;73import java.io.DataOutput;74import java.io.IOException;75import java.io.InvalidObjectException;76import java.io.ObjectInputStream;77import java.io.Serializable;78import java.time.chrono.Chronology;79import java.time.chrono.IsoChronology;80import java.time.format.DateTimeFormatter;81import java.time.format.DateTimeFormatterBuilder;82import java.time.format.DateTimeParseException;83import java.time.format.SignStyle;84import java.time.temporal.ChronoField;85import java.time.temporal.ChronoUnit;86import java.time.temporal.Temporal;87import java.time.temporal.TemporalAccessor;88import java.time.temporal.TemporalAdjuster;89import java.time.temporal.TemporalAmount;90import java.time.temporal.TemporalField;91import java.time.temporal.TemporalQueries;92import java.time.temporal.TemporalQuery;93import java.time.temporal.TemporalUnit;94import java.time.temporal.UnsupportedTemporalTypeException;95import java.time.temporal.ValueRange;96import java.util.Objects;9798/**99* A year in the ISO-8601 calendar system, such as {@code 2007}.100* <p>101* {@code Year} is an immutable date-time object that represents a year.102* Any field that can be derived from a year can be obtained.103* <p>104* <b>Note that years in the ISO chronology only align with years in the105* Gregorian-Julian system for modern years. Parts of Russia did not switch to the106* modern Gregorian/ISO rules until 1920.107* As such, historical years must be treated with caution.</b>108* <p>109* This class does not store or represent a month, day, time or time-zone.110* For example, the value "2007" can be stored in a {@code Year}.111* <p>112* Years represented by this class follow the ISO-8601 standard and use113* the proleptic numbering system. Year 1 is preceded by year 0, then by year -1.114* <p>115* The ISO-8601 calendar system is the modern civil calendar system used today116* in most of the world. It is equivalent to the proleptic Gregorian calendar117* system, in which today's rules for leap years are applied for all time.118* For most applications written today, the ISO-8601 rules are entirely suitable.119* However, any application that makes use of historical dates, and requires them120* to be accurate will find the ISO-8601 approach unsuitable.121*122* <p>123* This is a <a href="{@docRoot}/java/lang/doc-files/ValueBased.html">value-based</a>124* class; use of identity-sensitive operations (including reference equality125* ({@code ==}), identity hash code, or synchronization) on instances of126* {@code Year} may have unpredictable results and should be avoided.127* The {@code equals} method should be used for comparisons.128*129* @implSpec130* This class is immutable and thread-safe.131*132* @since 1.8133*/134public final class Year135implements Temporal, TemporalAdjuster, Comparable<Year>, Serializable {136137/**138* The minimum supported year, '-999,999,999'.139*/140public static final int MIN_VALUE = -999_999_999;141/**142* The maximum supported year, '+999,999,999'.143*/144public static final int MAX_VALUE = 999_999_999;145146/**147* Serialization version.148*/149private static final long serialVersionUID = -23038383694477807L;150/**151* Parser.152*/153private static final DateTimeFormatter PARSER = new DateTimeFormatterBuilder()154.appendValue(YEAR, 4, 10, SignStyle.EXCEEDS_PAD)155.toFormatter();156157/**158* The year being represented.159*/160private final int year;161162//-----------------------------------------------------------------------163/**164* Obtains the current year from the system clock in the default time-zone.165* <p>166* This will query the {@link Clock#systemDefaultZone() system clock} in the default167* time-zone to obtain the current year.168* <p>169* Using this method will prevent the ability to use an alternate clock for testing170* because the clock is hard-coded.171*172* @return the current year using the system clock and default time-zone, not null173*/174public static Year now() {175return now(Clock.systemDefaultZone());176}177178/**179* Obtains the current year from the system clock in the specified time-zone.180* <p>181* This will query the {@link Clock#system(ZoneId) system clock} to obtain the current year.182* Specifying the time-zone avoids dependence on the default time-zone.183* <p>184* Using this method will prevent the ability to use an alternate clock for testing185* because the clock is hard-coded.186*187* @param zone the zone ID to use, not null188* @return the current year using the system clock, not null189*/190public static Year now(ZoneId zone) {191return now(Clock.system(zone));192}193194/**195* Obtains the current year from the specified clock.196* <p>197* This will query the specified clock to obtain the current year.198* Using this method allows the use of an alternate clock for testing.199* The alternate clock may be introduced using {@link Clock dependency injection}.200*201* @param clock the clock to use, not null202* @return the current year, not null203*/204public static Year now(Clock clock) {205final LocalDate now = LocalDate.now(clock); // called once206return Year.of(now.getYear());207}208209//-----------------------------------------------------------------------210/**211* Obtains an instance of {@code Year}.212* <p>213* This method accepts a year value from the proleptic ISO calendar system.214* <p>215* The year 2AD/CE is represented by 2.<br>216* The year 1AD/CE is represented by 1.<br>217* The year 1BC/BCE is represented by 0.<br>218* The year 2BC/BCE is represented by -1.<br>219*220* @param isoYear the ISO proleptic year to represent, from {@code MIN_VALUE} to {@code MAX_VALUE}221* @return the year, not null222* @throws DateTimeException if the field is invalid223*/224public static Year of(int isoYear) {225YEAR.checkValidValue(isoYear);226return new Year(isoYear);227}228229//-----------------------------------------------------------------------230/**231* Obtains an instance of {@code Year} from a temporal object.232* <p>233* This obtains a year based on the specified temporal.234* A {@code TemporalAccessor} represents an arbitrary set of date and time information,235* which this factory converts to an instance of {@code Year}.236* <p>237* The conversion extracts the {@link ChronoField#YEAR year} field.238* The extraction is only permitted if the temporal object has an ISO239* chronology, or can be converted to a {@code LocalDate}.240* <p>241* This method matches the signature of the functional interface {@link TemporalQuery}242* allowing it to be used as a query via method reference, {@code Year::from}.243*244* @param temporal the temporal object to convert, not null245* @return the year, not null246* @throws DateTimeException if unable to convert to a {@code Year}247*/248public static Year from(TemporalAccessor temporal) {249if (temporal instanceof Year) {250return (Year) temporal;251}252Objects.requireNonNull(temporal, "temporal");253try {254if (IsoChronology.INSTANCE.equals(Chronology.from(temporal)) == false) {255temporal = LocalDate.from(temporal);256}257return of(temporal.get(YEAR));258} catch (DateTimeException ex) {259throw new DateTimeException("Unable to obtain Year from TemporalAccessor: " +260temporal + " of type " + temporal.getClass().getName(), ex);261}262}263264//-----------------------------------------------------------------------265/**266* Obtains an instance of {@code Year} from a text string such as {@code 2007}.267* <p>268* The string must represent a valid year.269* Years outside the range 0000 to 9999 must be prefixed by the plus or minus symbol.270*271* @param text the text to parse such as "2007", not null272* @return the parsed year, not null273* @throws DateTimeParseException if the text cannot be parsed274*/275public static Year parse(CharSequence text) {276return parse(text, PARSER);277}278279/**280* Obtains an instance of {@code Year} from a text string using a specific formatter.281* <p>282* The text is parsed using the formatter, returning a year.283*284* @param text the text to parse, not null285* @param formatter the formatter to use, not null286* @return the parsed year, not null287* @throws DateTimeParseException if the text cannot be parsed288*/289public static Year parse(CharSequence text, DateTimeFormatter formatter) {290Objects.requireNonNull(formatter, "formatter");291return formatter.parse(text, Year::from);292}293294//-------------------------------------------------------------------------295/**296* Checks if the year is a leap year, according to the ISO proleptic297* calendar system rules.298* <p>299* This method applies the current rules for leap years across the whole time-line.300* In general, a year is a leap year if it is divisible by four without301* remainder. However, years divisible by 100, are not leap years, with302* the exception of years divisible by 400 which are.303* <p>304* For example, 1904 is a leap year it is divisible by 4.305* 1900 was not a leap year as it is divisible by 100, however 2000 was a306* leap year as it is divisible by 400.307* <p>308* The calculation is proleptic - applying the same rules into the far future and far past.309* This is historically inaccurate, but is correct for the ISO-8601 standard.310*311* @param year the year to check312* @return true if the year is leap, false otherwise313*/314public static boolean isLeap(long year) {315return ((year & 3) == 0) && ((year % 100) != 0 || (year % 400) == 0);316}317318//-----------------------------------------------------------------------319/**320* Constructor.321*322* @param year the year to represent323*/324private Year(int year) {325this.year = year;326}327328//-----------------------------------------------------------------------329/**330* Gets the year value.331* <p>332* The year returned by this method is proleptic as per {@code get(YEAR)}.333*334* @return the year, {@code MIN_VALUE} to {@code MAX_VALUE}335*/336public int getValue() {337return year;338}339340//-----------------------------------------------------------------------341/**342* Checks if the specified field is supported.343* <p>344* This checks if this year can be queried for the specified field.345* If false, then calling the {@link #range(TemporalField) range},346* {@link #get(TemporalField) get} and {@link #with(TemporalField, long)}347* methods will throw an exception.348* <p>349* If the field is a {@link ChronoField} then the query is implemented here.350* The supported fields are:351* <ul>352* <li>{@code YEAR_OF_ERA}353* <li>{@code YEAR}354* <li>{@code ERA}355* </ul>356* All other {@code ChronoField} instances will return false.357* <p>358* If the field is not a {@code ChronoField}, then the result of this method359* is obtained by invoking {@code TemporalField.isSupportedBy(TemporalAccessor)}360* passing {@code this} as the argument.361* Whether the field is supported is determined by the field.362*363* @param field the field to check, null returns false364* @return true if the field is supported on this year, false if not365*/366@Override367public boolean isSupported(TemporalField field) {368if (field instanceof ChronoField) {369return field == YEAR || field == YEAR_OF_ERA || field == ERA;370}371return field != null && field.isSupportedBy(this);372}373374/**375* Checks if the specified unit is supported.376* <p>377* This checks if the specified unit can be added to, or subtracted from, this year.378* If false, then calling the {@link #plus(long, TemporalUnit)} and379* {@link #minus(long, TemporalUnit) minus} methods will throw an exception.380* <p>381* If the unit is a {@link ChronoUnit} then the query is implemented here.382* The supported units are:383* <ul>384* <li>{@code YEARS}385* <li>{@code DECADES}386* <li>{@code CENTURIES}387* <li>{@code MILLENNIA}388* <li>{@code ERAS}389* </ul>390* All other {@code ChronoUnit} instances will return false.391* <p>392* If the unit is not a {@code ChronoUnit}, then the result of this method393* is obtained by invoking {@code TemporalUnit.isSupportedBy(Temporal)}394* passing {@code this} as the argument.395* Whether the unit is supported is determined by the unit.396*397* @param unit the unit to check, null returns false398* @return true if the unit can be added/subtracted, false if not399*/400@Override401public boolean isSupported(TemporalUnit unit) {402if (unit instanceof ChronoUnit) {403return unit == YEARS || unit == DECADES || unit == CENTURIES || unit == MILLENNIA || unit == ERAS;404}405return unit != null && unit.isSupportedBy(this);406}407408//-----------------------------------------------------------------------409/**410* Gets the range of valid values for the specified field.411* <p>412* The range object expresses the minimum and maximum valid values for a field.413* This year is used to enhance the accuracy of the returned range.414* If it is not possible to return the range, because the field is not supported415* or for some other reason, an exception is thrown.416* <p>417* If the field is a {@link ChronoField} then the query is implemented here.418* The {@link #isSupported(TemporalField) supported fields} will return419* appropriate range instances.420* All other {@code ChronoField} instances will throw an {@code UnsupportedTemporalTypeException}.421* <p>422* If the field is not a {@code ChronoField}, then the result of this method423* is obtained by invoking {@code TemporalField.rangeRefinedBy(TemporalAccessor)}424* passing {@code this} as the argument.425* Whether the range can be obtained is determined by the field.426*427* @param field the field to query the range for, not null428* @return the range of valid values for the field, not null429* @throws DateTimeException if the range for the field cannot be obtained430* @throws UnsupportedTemporalTypeException if the field is not supported431*/432@Override433public ValueRange range(TemporalField field) {434if (field == YEAR_OF_ERA) {435return (year <= 0 ? ValueRange.of(1, MAX_VALUE + 1) : ValueRange.of(1, MAX_VALUE));436}437return Temporal.super.range(field);438}439440/**441* Gets the value of the specified field from this year as an {@code int}.442* <p>443* This queries this year for the value of the specified field.444* The returned value will always be within the valid range of values for the field.445* If it is not possible to return the value, because the field is not supported446* or for some other reason, an exception is thrown.447* <p>448* If the field is a {@link ChronoField} then the query is implemented here.449* The {@link #isSupported(TemporalField) supported fields} will return valid450* values based on this year.451* All other {@code ChronoField} instances will throw an {@code UnsupportedTemporalTypeException}.452* <p>453* If the field is not a {@code ChronoField}, then the result of this method454* is obtained by invoking {@code TemporalField.getFrom(TemporalAccessor)}455* passing {@code this} as the argument. Whether the value can be obtained,456* and what the value represents, is determined by the field.457*458* @param field the field to get, not null459* @return the value for the field460* @throws DateTimeException if a value for the field cannot be obtained or461* the value is outside the range of valid values for the field462* @throws UnsupportedTemporalTypeException if the field is not supported or463* the range of values exceeds an {@code int}464* @throws ArithmeticException if numeric overflow occurs465*/466@Override // override for Javadoc467public int get(TemporalField field) {468return range(field).checkValidIntValue(getLong(field), field);469}470471/**472* Gets the value of the specified field from this year as a {@code long}.473* <p>474* This queries this year for the value of the specified field.475* If it is not possible to return the value, because the field is not supported476* or for some other reason, an exception is thrown.477* <p>478* If the field is a {@link ChronoField} then the query is implemented here.479* The {@link #isSupported(TemporalField) supported fields} will return valid480* values based on this year.481* All other {@code ChronoField} instances will throw an {@code UnsupportedTemporalTypeException}.482* <p>483* If the field is not a {@code ChronoField}, then the result of this method484* is obtained by invoking {@code TemporalField.getFrom(TemporalAccessor)}485* passing {@code this} as the argument. Whether the value can be obtained,486* and what the value represents, is determined by the field.487*488* @param field the field to get, not null489* @return the value for the field490* @throws DateTimeException if a value for the field cannot be obtained491* @throws UnsupportedTemporalTypeException if the field is not supported492* @throws ArithmeticException if numeric overflow occurs493*/494@Override495public long getLong(TemporalField field) {496if (field instanceof ChronoField) {497switch ((ChronoField) field) {498case YEAR_OF_ERA: return (year < 1 ? 1 - year : year);499case YEAR: return year;500case ERA: return (year < 1 ? 0 : 1);501}502throw new UnsupportedTemporalTypeException("Unsupported field: " + field);503}504return field.getFrom(this);505}506507//-----------------------------------------------------------------------508/**509* Checks if the year is a leap year, according to the ISO proleptic510* calendar system rules.511* <p>512* This method applies the current rules for leap years across the whole time-line.513* In general, a year is a leap year if it is divisible by four without514* remainder. However, years divisible by 100, are not leap years, with515* the exception of years divisible by 400 which are.516* <p>517* For example, 1904 is a leap year it is divisible by 4.518* 1900 was not a leap year as it is divisible by 100, however 2000 was a519* leap year as it is divisible by 400.520* <p>521* The calculation is proleptic - applying the same rules into the far future and far past.522* This is historically inaccurate, but is correct for the ISO-8601 standard.523*524* @return true if the year is leap, false otherwise525*/526public boolean isLeap() {527return Year.isLeap(year);528}529530/**531* Checks if the month-day is valid for this year.532* <p>533* This method checks whether this year and the input month and day form534* a valid date.535*536* @param monthDay the month-day to validate, null returns false537* @return true if the month and day are valid for this year538*/539public boolean isValidMonthDay(MonthDay monthDay) {540return monthDay != null && monthDay.isValidYear(year);541}542543/**544* Gets the length of this year in days.545*546* @return the length of this year in days, 365 or 366547*/548public int length() {549return isLeap() ? 366 : 365;550}551552//-----------------------------------------------------------------------553/**554* Returns an adjusted copy of this year.555* <p>556* This returns a {@code Year}, based on this one, with the year adjusted.557* The adjustment takes place using the specified adjuster strategy object.558* Read the documentation of the adjuster to understand what adjustment will be made.559* <p>560* The result of this method is obtained by invoking the561* {@link TemporalAdjuster#adjustInto(Temporal)} method on the562* specified adjuster passing {@code this} as the argument.563* <p>564* This instance is immutable and unaffected by this method call.565*566* @param adjuster the adjuster to use, not null567* @return a {@code Year} based on {@code this} with the adjustment made, not null568* @throws DateTimeException if the adjustment cannot be made569* @throws ArithmeticException if numeric overflow occurs570*/571@Override572public Year with(TemporalAdjuster adjuster) {573return (Year) adjuster.adjustInto(this);574}575576/**577* Returns a copy of this year with the specified field set to a new value.578* <p>579* This returns a {@code Year}, based on this one, with the value580* for the specified field changed.581* If it is not possible to set the value, because the field is not supported or for582* some other reason, an exception is thrown.583* <p>584* If the field is a {@link ChronoField} then the adjustment is implemented here.585* The supported fields behave as follows:586* <ul>587* <li>{@code YEAR_OF_ERA} -588* Returns a {@code Year} with the specified year-of-era589* The era will be unchanged.590* <li>{@code YEAR} -591* Returns a {@code Year} with the specified year.592* This completely replaces the date and is equivalent to {@link #of(int)}.593* <li>{@code ERA} -594* Returns a {@code Year} with the specified era.595* The year-of-era will be unchanged.596* </ul>597* <p>598* In all cases, if the new value is outside the valid range of values for the field599* then a {@code DateTimeException} will be thrown.600* <p>601* All other {@code ChronoField} instances will throw an {@code UnsupportedTemporalTypeException}.602* <p>603* If the field is not a {@code ChronoField}, then the result of this method604* is obtained by invoking {@code TemporalField.adjustInto(Temporal, long)}605* passing {@code this} as the argument. In this case, the field determines606* whether and how to adjust the instant.607* <p>608* This instance is immutable and unaffected by this method call.609*610* @param field the field to set in the result, not null611* @param newValue the new value of the field in the result612* @return a {@code Year} based on {@code this} with the specified field set, not null613* @throws DateTimeException if the field cannot be set614* @throws UnsupportedTemporalTypeException if the field is not supported615* @throws ArithmeticException if numeric overflow occurs616*/617@Override618public Year with(TemporalField field, long newValue) {619if (field instanceof ChronoField) {620ChronoField f = (ChronoField) field;621f.checkValidValue(newValue);622switch (f) {623case YEAR_OF_ERA: return Year.of((int) (year < 1 ? 1 - newValue : newValue));624case YEAR: return Year.of((int) newValue);625case ERA: return (getLong(ERA) == newValue ? this : Year.of(1 - year));626}627throw new UnsupportedTemporalTypeException("Unsupported field: " + field);628}629return field.adjustInto(this, newValue);630}631632//-----------------------------------------------------------------------633/**634* Returns a copy of this year with the specified amount added.635* <p>636* This returns a {@code Year}, based on this one, with the specified amount added.637* The amount is typically {@link Period} but may be any other type implementing638* the {@link TemporalAmount} interface.639* <p>640* The calculation is delegated to the amount object by calling641* {@link TemporalAmount#addTo(Temporal)}. The amount implementation is free642* to implement the addition in any way it wishes, however it typically643* calls back to {@link #plus(long, TemporalUnit)}. Consult the documentation644* of the amount implementation to determine if it can be successfully added.645* <p>646* This instance is immutable and unaffected by this method call.647*648* @param amountToAdd the amount to add, not null649* @return a {@code Year} based on this year with the addition made, not null650* @throws DateTimeException if the addition cannot be made651* @throws ArithmeticException if numeric overflow occurs652*/653@Override654public Year plus(TemporalAmount amountToAdd) {655return (Year) amountToAdd.addTo(this);656}657658/**659* Returns a copy of this year with the specified amount added.660* <p>661* This returns a {@code Year}, based on this one, with the amount662* in terms of the unit added. If it is not possible to add the amount, because the663* unit is not supported or for some other reason, an exception is thrown.664* <p>665* If the field is a {@link ChronoUnit} then the addition is implemented here.666* The supported fields behave as follows:667* <ul>668* <li>{@code YEARS} -669* Returns a {@code Year} with the specified number of years added.670* This is equivalent to {@link #plusYears(long)}.671* <li>{@code DECADES} -672* Returns a {@code Year} with the specified number of decades added.673* This is equivalent to calling {@link #plusYears(long)} with the amount674* multiplied by 10.675* <li>{@code CENTURIES} -676* Returns a {@code Year} with the specified number of centuries added.677* This is equivalent to calling {@link #plusYears(long)} with the amount678* multiplied by 100.679* <li>{@code MILLENNIA} -680* Returns a {@code Year} with the specified number of millennia added.681* This is equivalent to calling {@link #plusYears(long)} with the amount682* multiplied by 1,000.683* <li>{@code ERAS} -684* Returns a {@code Year} with the specified number of eras added.685* Only two eras are supported so the amount must be one, zero or minus one.686* If the amount is non-zero then the year is changed such that the year-of-era687* is unchanged.688* </ul>689* <p>690* All other {@code ChronoUnit} instances will throw an {@code UnsupportedTemporalTypeException}.691* <p>692* If the field is not a {@code ChronoUnit}, then the result of this method693* is obtained by invoking {@code TemporalUnit.addTo(Temporal, long)}694* passing {@code this} as the argument. In this case, the unit determines695* whether and how to perform the addition.696* <p>697* This instance is immutable and unaffected by this method call.698*699* @param amountToAdd the amount of the unit to add to the result, may be negative700* @param unit the unit of the amount to add, not null701* @return a {@code Year} based on this year with the specified amount added, not null702* @throws DateTimeException if the addition cannot be made703* @throws UnsupportedTemporalTypeException if the unit is not supported704* @throws ArithmeticException if numeric overflow occurs705*/706@Override707public Year plus(long amountToAdd, TemporalUnit unit) {708if (unit instanceof ChronoUnit) {709switch ((ChronoUnit) unit) {710case YEARS: return plusYears(amountToAdd);711case DECADES: return plusYears(Math.multiplyExact(amountToAdd, 10));712case CENTURIES: return plusYears(Math.multiplyExact(amountToAdd, 100));713case MILLENNIA: return plusYears(Math.multiplyExact(amountToAdd, 1000));714case ERAS: return with(ERA, Math.addExact(getLong(ERA), amountToAdd));715}716throw new UnsupportedTemporalTypeException("Unsupported unit: " + unit);717}718return unit.addTo(this, amountToAdd);719}720721/**722* Returns a copy of this {@code Year} with the specified number of years added.723* <p>724* This instance is immutable and unaffected by this method call.725*726* @param yearsToAdd the years to add, may be negative727* @return a {@code Year} based on this year with the years added, not null728* @throws DateTimeException if the result exceeds the supported range729*/730public Year plusYears(long yearsToAdd) {731if (yearsToAdd == 0) {732return this;733}734return of(YEAR.checkValidIntValue(year + yearsToAdd)); // overflow safe735}736737//-----------------------------------------------------------------------738/**739* Returns a copy of this year with the specified amount subtracted.740* <p>741* This returns a {@code Year}, based on this one, with the specified amount subtracted.742* The amount is typically {@link Period} but may be any other type implementing743* the {@link TemporalAmount} interface.744* <p>745* The calculation is delegated to the amount object by calling746* {@link TemporalAmount#subtractFrom(Temporal)}. The amount implementation is free747* to implement the subtraction in any way it wishes, however it typically748* calls back to {@link #minus(long, TemporalUnit)}. Consult the documentation749* of the amount implementation to determine if it can be successfully subtracted.750* <p>751* This instance is immutable and unaffected by this method call.752*753* @param amountToSubtract the amount to subtract, not null754* @return a {@code Year} based on this year with the subtraction made, not null755* @throws DateTimeException if the subtraction cannot be made756* @throws ArithmeticException if numeric overflow occurs757*/758@Override759public Year minus(TemporalAmount amountToSubtract) {760return (Year) amountToSubtract.subtractFrom(this);761}762763/**764* Returns a copy of this year with the specified amount subtracted.765* <p>766* This returns a {@code Year}, based on this one, with the amount767* in terms of the unit subtracted. If it is not possible to subtract the amount,768* because the unit is not supported or for some other reason, an exception is thrown.769* <p>770* This method is equivalent to {@link #plus(long, TemporalUnit)} with the amount negated.771* See that method for a full description of how addition, and thus subtraction, works.772* <p>773* This instance is immutable and unaffected by this method call.774*775* @param amountToSubtract the amount of the unit to subtract from the result, may be negative776* @param unit the unit of the amount to subtract, not null777* @return a {@code Year} based on this year with the specified amount subtracted, not null778* @throws DateTimeException if the subtraction cannot be made779* @throws UnsupportedTemporalTypeException if the unit is not supported780* @throws ArithmeticException if numeric overflow occurs781*/782@Override783public Year minus(long amountToSubtract, TemporalUnit unit) {784return (amountToSubtract == Long.MIN_VALUE ? plus(Long.MAX_VALUE, unit).plus(1, unit) : plus(-amountToSubtract, unit));785}786787/**788* Returns a copy of this {@code Year} with the specified number of years subtracted.789* <p>790* This instance is immutable and unaffected by this method call.791*792* @param yearsToSubtract the years to subtract, may be negative793* @return a {@code Year} based on this year with the year subtracted, not null794* @throws DateTimeException if the result exceeds the supported range795*/796public Year minusYears(long yearsToSubtract) {797return (yearsToSubtract == Long.MIN_VALUE ? plusYears(Long.MAX_VALUE).plusYears(1) : plusYears(-yearsToSubtract));798}799800//-----------------------------------------------------------------------801/**802* Queries this year using the specified query.803* <p>804* This queries this year using the specified query strategy object.805* The {@code TemporalQuery} object defines the logic to be used to806* obtain the result. Read the documentation of the query to understand807* what the result of this method will be.808* <p>809* The result of this method is obtained by invoking the810* {@link TemporalQuery#queryFrom(TemporalAccessor)} method on the811* specified query passing {@code this} as the argument.812*813* @param <R> the type of the result814* @param query the query to invoke, not null815* @return the query result, null may be returned (defined by the query)816* @throws DateTimeException if unable to query (defined by the query)817* @throws ArithmeticException if numeric overflow occurs (defined by the query)818*/819@SuppressWarnings("unchecked")820@Override821public <R> R query(TemporalQuery<R> query) {822if (query == TemporalQueries.chronology()) {823return (R) IsoChronology.INSTANCE;824} else if (query == TemporalQueries.precision()) {825return (R) YEARS;826}827return Temporal.super.query(query);828}829830/**831* Adjusts the specified temporal object to have this year.832* <p>833* This returns a temporal object of the same observable type as the input834* with the year changed to be the same as this.835* <p>836* The adjustment is equivalent to using {@link Temporal#with(TemporalField, long)}837* passing {@link ChronoField#YEAR} as the field.838* If the specified temporal object does not use the ISO calendar system then839* a {@code DateTimeException} is thrown.840* <p>841* In most cases, it is clearer to reverse the calling pattern by using842* {@link Temporal#with(TemporalAdjuster)}:843* <pre>844* // these two lines are equivalent, but the second approach is recommended845* temporal = thisYear.adjustInto(temporal);846* temporal = temporal.with(thisYear);847* </pre>848* <p>849* This instance is immutable and unaffected by this method call.850*851* @param temporal the target object to be adjusted, not null852* @return the adjusted object, not null853* @throws DateTimeException if unable to make the adjustment854* @throws ArithmeticException if numeric overflow occurs855*/856@Override857public Temporal adjustInto(Temporal temporal) {858if (Chronology.from(temporal).equals(IsoChronology.INSTANCE) == false) {859throw new DateTimeException("Adjustment only supported on ISO date-time");860}861return temporal.with(YEAR, year);862}863864/**865* Calculates the amount of time until another year in terms of the specified unit.866* <p>867* This calculates the amount of time between two {@code Year}868* objects in terms of a single {@code TemporalUnit}.869* The start and end points are {@code this} and the specified year.870* The result will be negative if the end is before the start.871* The {@code Temporal} passed to this method is converted to a872* {@code Year} using {@link #from(TemporalAccessor)}.873* For example, the amount in decades between two year can be calculated874* using {@code startYear.until(endYear, DECADES)}.875* <p>876* The calculation returns a whole number, representing the number of877* complete units between the two years.878* For example, the amount in decades between 2012 and 2031879* will only be one decade as it is one year short of two decades.880* <p>881* There are two equivalent ways of using this method.882* The first is to invoke this method.883* The second is to use {@link TemporalUnit#between(Temporal, Temporal)}:884* <pre>885* // these two lines are equivalent886* amount = start.until(end, YEARS);887* amount = YEARS.between(start, end);888* </pre>889* The choice should be made based on which makes the code more readable.890* <p>891* The calculation is implemented in this method for {@link ChronoUnit}.892* The units {@code YEARS}, {@code DECADES}, {@code CENTURIES},893* {@code MILLENNIA} and {@code ERAS} are supported.894* Other {@code ChronoUnit} values will throw an exception.895* <p>896* If the unit is not a {@code ChronoUnit}, then the result of this method897* is obtained by invoking {@code TemporalUnit.between(Temporal, Temporal)}898* passing {@code this} as the first argument and the converted input temporal899* as the second argument.900* <p>901* This instance is immutable and unaffected by this method call.902*903* @param endExclusive the end date, exclusive, which is converted to a {@code Year}, not null904* @param unit the unit to measure the amount in, not null905* @return the amount of time between this year and the end year906* @throws DateTimeException if the amount cannot be calculated, or the end907* temporal cannot be converted to a {@code Year}908* @throws UnsupportedTemporalTypeException if the unit is not supported909* @throws ArithmeticException if numeric overflow occurs910*/911@Override912public long until(Temporal endExclusive, TemporalUnit unit) {913Year end = Year.from(endExclusive);914if (unit instanceof ChronoUnit) {915long yearsUntil = ((long) end.year) - year; // no overflow916switch ((ChronoUnit) unit) {917case YEARS: return yearsUntil;918case DECADES: return yearsUntil / 10;919case CENTURIES: return yearsUntil / 100;920case MILLENNIA: return yearsUntil / 1000;921case ERAS: return end.getLong(ERA) - getLong(ERA);922}923throw new UnsupportedTemporalTypeException("Unsupported unit: " + unit);924}925return unit.between(this, end);926}927928/**929* Formats this year using the specified formatter.930* <p>931* This year will be passed to the formatter to produce a string.932*933* @param formatter the formatter to use, not null934* @return the formatted year string, not null935* @throws DateTimeException if an error occurs during printing936*/937public String format(DateTimeFormatter formatter) {938Objects.requireNonNull(formatter, "formatter");939return formatter.format(this);940}941942//-----------------------------------------------------------------------943/**944* Combines this year with a day-of-year to create a {@code LocalDate}.945* <p>946* This returns a {@code LocalDate} formed from this year and the specified day-of-year.947* <p>948* The day-of-year value 366 is only valid in a leap year.949*950* @param dayOfYear the day-of-year to use, from 1 to 365-366951* @return the local date formed from this year and the specified date of year, not null952* @throws DateTimeException if the day of year is zero or less, 366 or greater or equal953* to 366 and this is not a leap year954*/955public LocalDate atDay(int dayOfYear) {956return LocalDate.ofYearDay(year, dayOfYear);957}958959/**960* Combines this year with a month to create a {@code YearMonth}.961* <p>962* This returns a {@code YearMonth} formed from this year and the specified month.963* All possible combinations of year and month are valid.964* <p>965* This method can be used as part of a chain to produce a date:966* <pre>967* LocalDate date = year.atMonth(month).atDay(day);968* </pre>969*970* @param month the month-of-year to use, not null971* @return the year-month formed from this year and the specified month, not null972*/973public YearMonth atMonth(Month month) {974return YearMonth.of(year, month);975}976977/**978* Combines this year with a month to create a {@code YearMonth}.979* <p>980* This returns a {@code YearMonth} formed from this year and the specified month.981* All possible combinations of year and month are valid.982* <p>983* This method can be used as part of a chain to produce a date:984* <pre>985* LocalDate date = year.atMonth(month).atDay(day);986* </pre>987*988* @param month the month-of-year to use, from 1 (January) to 12 (December)989* @return the year-month formed from this year and the specified month, not null990* @throws DateTimeException if the month is invalid991*/992public YearMonth atMonth(int month) {993return YearMonth.of(year, month);994}995996/**997* Combines this year with a month-day to create a {@code LocalDate}.998* <p>999* This returns a {@code LocalDate} formed from this year and the specified month-day.1000* <p>1001* A month-day of February 29th will be adjusted to February 28th in the resulting1002* date if the year is not a leap year.1003*1004* @param monthDay the month-day to use, not null1005* @return the local date formed from this year and the specified month-day, not null1006*/1007public LocalDate atMonthDay(MonthDay monthDay) {1008return monthDay.atYear(year);1009}10101011//-----------------------------------------------------------------------1012/**1013* Compares this year to another year.1014* <p>1015* The comparison is based on the value of the year.1016* It is "consistent with equals", as defined by {@link Comparable}.1017*1018* @param other the other year to compare to, not null1019* @return the comparator value, negative if less, positive if greater1020*/1021@Override1022public int compareTo(Year other) {1023return year - other.year;1024}10251026/**1027* Checks if this year is after the specified year.1028*1029* @param other the other year to compare to, not null1030* @return true if this is after the specified year1031*/1032public boolean isAfter(Year other) {1033return year > other.year;1034}10351036/**1037* Checks if this year is before the specified year.1038*1039* @param other the other year to compare to, not null1040* @return true if this point is before the specified year1041*/1042public boolean isBefore(Year other) {1043return year < other.year;1044}10451046//-----------------------------------------------------------------------1047/**1048* Checks if this year is equal to another year.1049* <p>1050* The comparison is based on the time-line position of the years.1051*1052* @param obj the object to check, null returns false1053* @return true if this is equal to the other year1054*/1055@Override1056public boolean equals(Object obj) {1057if (this == obj) {1058return true;1059}1060if (obj instanceof Year) {1061return year == ((Year) obj).year;1062}1063return false;1064}10651066/**1067* A hash code for this year.1068*1069* @return a suitable hash code1070*/1071@Override1072public int hashCode() {1073return year;1074}10751076//-----------------------------------------------------------------------1077/**1078* Outputs this year as a {@code String}.1079*1080* @return a string representation of this year, not null1081*/1082@Override1083public String toString() {1084return Integer.toString(year);1085}10861087//-----------------------------------------------------------------------1088/**1089* Writes the object using a1090* <a href="../../serialized-form.html#java.time.Ser">dedicated serialized form</a>.1091* @serialData1092* <pre>1093* out.writeByte(11); // identifies a Year1094* out.writeInt(year);1095* </pre>1096*1097* @return the instance of {@code Ser}, not null1098*/1099private Object writeReplace() {1100return new Ser(Ser.YEAR_TYPE, this);1101}11021103/**1104* Defend against malicious streams.1105*1106* @param s the stream to read1107* @throws InvalidObjectException always1108*/1109private void readObject(ObjectInputStream s) throws InvalidObjectException {1110throw new InvalidObjectException("Deserialization via serialization delegate");1111}11121113void writeExternal(DataOutput out) throws IOException {1114out.writeInt(year);1115}11161117static Year readExternal(DataInput in) throws IOException {1118return Year.of(in.readInt());1119}11201121}112211231124