Path: blob/master/src/java.base/share/classes/java/time/Year.java
41152 views
/*1* Copyright (c) 2012, 2020, 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* <p>122* This is a <a href="{@docRoot}/java.base/java/lang/doc-files/ValueBased.html">value-based</a>123* class; programmers should treat instances that are124* {@linkplain #equals(Object) equal} as interchangeable and should not125* use instances for synchronization, or unpredictable behavior may126* occur. For example, in a future release, synchronization may fail.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*/134@jdk.internal.ValueBased135public final class Year136implements Temporal, TemporalAdjuster, Comparable<Year>, Serializable {137138/**139* The minimum supported year, '-999,999,999'.140*/141public static final int MIN_VALUE = -999_999_999;142/**143* The maximum supported year, '+999,999,999'.144*/145public static final int MAX_VALUE = 999_999_999;146147/**148* Serialization version.149*/150@java.io.Serial151private static final long serialVersionUID = -23038383694477807L;152/**153* Parser.154*/155private static final DateTimeFormatter PARSER = new DateTimeFormatterBuilder()156.parseLenient()157.appendValue(YEAR, 1, 10, SignStyle.NORMAL)158.toFormatter();159160/**161* The year being represented.162*/163private final int year;164165//-----------------------------------------------------------------------166/**167* Obtains the current year from the system clock in the default time-zone.168* <p>169* This will query the {@link Clock#systemDefaultZone() system clock} in the default170* time-zone to obtain the current year.171* <p>172* Using this method will prevent the ability to use an alternate clock for testing173* because the clock is hard-coded.174*175* @return the current year using the system clock and default time-zone, not null176*/177public static Year now() {178return now(Clock.systemDefaultZone());179}180181/**182* Obtains the current year from the system clock in the specified time-zone.183* <p>184* This will query the {@link Clock#system(ZoneId) system clock} to obtain the current year.185* Specifying the time-zone avoids dependence on the default time-zone.186* <p>187* Using this method will prevent the ability to use an alternate clock for testing188* because the clock is hard-coded.189*190* @param zone the zone ID to use, not null191* @return the current year using the system clock, not null192*/193public static Year now(ZoneId zone) {194return now(Clock.system(zone));195}196197/**198* Obtains the current year from the specified clock.199* <p>200* This will query the specified clock to obtain the current year.201* Using this method allows the use of an alternate clock for testing.202* The alternate clock may be introduced using {@link Clock dependency injection}.203*204* @param clock the clock to use, not null205* @return the current year, not null206*/207public static Year now(Clock clock) {208final LocalDate now = LocalDate.now(clock); // called once209return Year.of(now.getYear());210}211212//-----------------------------------------------------------------------213/**214* Obtains an instance of {@code Year}.215* <p>216* This method accepts a year value from the proleptic ISO calendar system.217* <p>218* The year 2AD/CE is represented by 2.<br>219* The year 1AD/CE is represented by 1.<br>220* The year 1BC/BCE is represented by 0.<br>221* The year 2BC/BCE is represented by -1.<br>222*223* @param isoYear the ISO proleptic year to represent, from {@code MIN_VALUE} to {@code MAX_VALUE}224* @return the year, not null225* @throws DateTimeException if the field is invalid226*/227public static Year of(int isoYear) {228YEAR.checkValidValue(isoYear);229return new Year(isoYear);230}231232//-----------------------------------------------------------------------233/**234* Obtains an instance of {@code Year} from a temporal object.235* <p>236* This obtains a year based on the specified temporal.237* A {@code TemporalAccessor} represents an arbitrary set of date and time information,238* which this factory converts to an instance of {@code Year}.239* <p>240* The conversion extracts the {@link ChronoField#YEAR year} field.241* The extraction is only permitted if the temporal object has an ISO242* chronology, or can be converted to a {@code LocalDate}.243* <p>244* This method matches the signature of the functional interface {@link TemporalQuery}245* allowing it to be used as a query via method reference, {@code Year::from}.246*247* @param temporal the temporal object to convert, not null248* @return the year, not null249* @throws DateTimeException if unable to convert to a {@code Year}250*/251public static Year from(TemporalAccessor temporal) {252if (temporal instanceof Year) {253return (Year) temporal;254}255Objects.requireNonNull(temporal, "temporal");256try {257if (IsoChronology.INSTANCE.equals(Chronology.from(temporal)) == false) {258temporal = LocalDate.from(temporal);259}260return of(temporal.get(YEAR));261} catch (DateTimeException ex) {262throw new DateTimeException("Unable to obtain Year from TemporalAccessor: " +263temporal + " of type " + temporal.getClass().getName(), ex);264}265}266267//-----------------------------------------------------------------------268/**269* Obtains an instance of {@code Year} from a text string such as {@code 2007}.270* <p>271* The string must represent a valid year.272*273* @param text the text to parse such as "2007", not null274* @return the parsed year, not null275* @throws DateTimeParseException if the text cannot be parsed276*/277public static Year parse(CharSequence text) {278return parse(text, PARSER);279}280281/**282* Obtains an instance of {@code Year} from a text string using a specific formatter.283* <p>284* The text is parsed using the formatter, returning a year.285*286* @param text the text to parse, not null287* @param formatter the formatter to use, not null288* @return the parsed year, not null289* @throws DateTimeParseException if the text cannot be parsed290*/291public static Year parse(CharSequence text, DateTimeFormatter formatter) {292Objects.requireNonNull(formatter, "formatter");293return formatter.parse(text, Year::from);294}295296//-------------------------------------------------------------------------297/**298* Checks if the year is a leap year, according to the ISO proleptic299* calendar system rules.300* <p>301* This method applies the current rules for leap years across the whole time-line.302* In general, a year is a leap year if it is divisible by four without303* remainder. However, years divisible by 100, are not leap years, with304* the exception of years divisible by 400 which are.305* <p>306* For example, 1904 is a leap year it is divisible by 4.307* 1900 was not a leap year as it is divisible by 100, however 2000 was a308* leap year as it is divisible by 400.309* <p>310* The calculation is proleptic - applying the same rules into the far future and far past.311* This is historically inaccurate, but is correct for the ISO-8601 standard.312*313* @param year the year to check314* @return true if the year is leap, false otherwise315*/316public static boolean isLeap(long year) {317return ((year & 3) == 0) && ((year % 100) != 0 || (year % 400) == 0);318}319320//-----------------------------------------------------------------------321/**322* Constructor.323*324* @param year the year to represent325*/326private Year(int year) {327this.year = year;328}329330//-----------------------------------------------------------------------331/**332* Gets the year value.333* <p>334* The year returned by this method is proleptic as per {@code get(YEAR)}.335*336* @return the year, {@code MIN_VALUE} to {@code MAX_VALUE}337*/338public int getValue() {339return year;340}341342//-----------------------------------------------------------------------343/**344* Checks if the specified field is supported.345* <p>346* This checks if this year can be queried for the specified field.347* If false, then calling the {@link #range(TemporalField) range},348* {@link #get(TemporalField) get} and {@link #with(TemporalField, long)}349* methods will throw an exception.350* <p>351* If the field is a {@link ChronoField} then the query is implemented here.352* The supported fields are:353* <ul>354* <li>{@code YEAR_OF_ERA}355* <li>{@code YEAR}356* <li>{@code ERA}357* </ul>358* All other {@code ChronoField} instances will return false.359* <p>360* If the field is not a {@code ChronoField}, then the result of this method361* is obtained by invoking {@code TemporalField.isSupportedBy(TemporalAccessor)}362* passing {@code this} as the argument.363* Whether the field is supported is determined by the field.364*365* @param field the field to check, null returns false366* @return true if the field is supported on this year, false if not367*/368@Override369public boolean isSupported(TemporalField field) {370if (field instanceof ChronoField) {371return field == YEAR || field == YEAR_OF_ERA || field == ERA;372}373return field != null && field.isSupportedBy(this);374}375376/**377* Checks if the specified unit is supported.378* <p>379* This checks if the specified unit can be added to, or subtracted from, this year.380* If false, then calling the {@link #plus(long, TemporalUnit)} and381* {@link #minus(long, TemporalUnit) minus} methods will throw an exception.382* <p>383* If the unit is a {@link ChronoUnit} then the query is implemented here.384* The supported units are:385* <ul>386* <li>{@code YEARS}387* <li>{@code DECADES}388* <li>{@code CENTURIES}389* <li>{@code MILLENNIA}390* <li>{@code ERAS}391* </ul>392* All other {@code ChronoUnit} instances will return false.393* <p>394* If the unit is not a {@code ChronoUnit}, then the result of this method395* is obtained by invoking {@code TemporalUnit.isSupportedBy(Temporal)}396* passing {@code this} as the argument.397* Whether the unit is supported is determined by the unit.398*399* @param unit the unit to check, null returns false400* @return true if the unit can be added/subtracted, false if not401*/402@Override403public boolean isSupported(TemporalUnit unit) {404if (unit instanceof ChronoUnit) {405return unit == YEARS || unit == DECADES || unit == CENTURIES || unit == MILLENNIA || unit == ERAS;406}407return unit != null && unit.isSupportedBy(this);408}409410//-----------------------------------------------------------------------411/**412* Gets the range of valid values for the specified field.413* <p>414* The range object expresses the minimum and maximum valid values for a field.415* This year is used to enhance the accuracy of the returned range.416* If it is not possible to return the range, because the field is not supported417* or for some other reason, an exception is thrown.418* <p>419* If the field is a {@link ChronoField} then the query is implemented here.420* The {@link #isSupported(TemporalField) supported fields} will return421* appropriate range instances.422* All other {@code ChronoField} instances will throw an {@code UnsupportedTemporalTypeException}.423* <p>424* If the field is not a {@code ChronoField}, then the result of this method425* is obtained by invoking {@code TemporalField.rangeRefinedBy(TemporalAccessor)}426* passing {@code this} as the argument.427* Whether the range can be obtained is determined by the field.428*429* @param field the field to query the range for, not null430* @return the range of valid values for the field, not null431* @throws DateTimeException if the range for the field cannot be obtained432* @throws UnsupportedTemporalTypeException if the field is not supported433*/434@Override435public ValueRange range(TemporalField field) {436if (field == YEAR_OF_ERA) {437return (year <= 0 ? ValueRange.of(1, MAX_VALUE + 1) : ValueRange.of(1, MAX_VALUE));438}439return Temporal.super.range(field);440}441442/**443* Gets the value of the specified field from this year as an {@code int}.444* <p>445* This queries this year for the value of the specified field.446* The returned value will always be within the valid range of values for the field.447* If it is not possible to return the value, because the field is not supported448* or for some other reason, an exception is thrown.449* <p>450* If the field is a {@link ChronoField} then the query is implemented here.451* The {@link #isSupported(TemporalField) supported fields} will return valid452* values based on this year.453* All other {@code ChronoField} instances will throw an {@code UnsupportedTemporalTypeException}.454* <p>455* If the field is not a {@code ChronoField}, then the result of this method456* is obtained by invoking {@code TemporalField.getFrom(TemporalAccessor)}457* passing {@code this} as the argument. Whether the value can be obtained,458* and what the value represents, is determined by the field.459*460* @param field the field to get, not null461* @return the value for the field462* @throws DateTimeException if a value for the field cannot be obtained or463* the value is outside the range of valid values for the field464* @throws UnsupportedTemporalTypeException if the field is not supported or465* the range of values exceeds an {@code int}466* @throws ArithmeticException if numeric overflow occurs467*/468@Override // override for Javadoc469public int get(TemporalField field) {470return range(field).checkValidIntValue(getLong(field), field);471}472473/**474* Gets the value of the specified field from this year as a {@code long}.475* <p>476* This queries this year for the value of the specified field.477* If it is not possible to return the value, because the field is not supported478* or for some other reason, an exception is thrown.479* <p>480* If the field is a {@link ChronoField} then the query is implemented here.481* The {@link #isSupported(TemporalField) supported fields} will return valid482* values based on this year.483* All other {@code ChronoField} instances will throw an {@code UnsupportedTemporalTypeException}.484* <p>485* If the field is not a {@code ChronoField}, then the result of this method486* is obtained by invoking {@code TemporalField.getFrom(TemporalAccessor)}487* passing {@code this} as the argument. Whether the value can be obtained,488* and what the value represents, is determined by the field.489*490* @param field the field to get, not null491* @return the value for the field492* @throws DateTimeException if a value for the field cannot be obtained493* @throws UnsupportedTemporalTypeException if the field is not supported494* @throws ArithmeticException if numeric overflow occurs495*/496@Override497public long getLong(TemporalField field) {498if (field instanceof ChronoField chronoField) {499switch (chronoField) {500case YEAR_OF_ERA: return (year < 1 ? 1 - year : year);501case YEAR: return year;502case ERA: return (year < 1 ? 0 : 1);503}504throw new UnsupportedTemporalTypeException("Unsupported field: " + field);505}506return field.getFrom(this);507}508509//-----------------------------------------------------------------------510/**511* Checks if the year is a leap year, according to the ISO proleptic512* calendar system rules.513* <p>514* This method applies the current rules for leap years across the whole time-line.515* In general, a year is a leap year if it is divisible by four without516* remainder. However, years divisible by 100, are not leap years, with517* the exception of years divisible by 400 which are.518* <p>519* For example, 1904 is a leap year it is divisible by 4.520* 1900 was not a leap year as it is divisible by 100, however 2000 was a521* leap year as it is divisible by 400.522* <p>523* The calculation is proleptic - applying the same rules into the far future and far past.524* This is historically inaccurate, but is correct for the ISO-8601 standard.525*526* @return true if the year is leap, false otherwise527*/528public boolean isLeap() {529return Year.isLeap(year);530}531532/**533* Checks if the month-day is valid for this year.534* <p>535* This method checks whether this year and the input month and day form536* a valid date.537*538* @param monthDay the month-day to validate, null returns false539* @return true if the month and day are valid for this year540*/541public boolean isValidMonthDay(MonthDay monthDay) {542return monthDay != null && monthDay.isValidYear(year);543}544545/**546* Gets the length of this year in days.547*548* @return the length of this year in days, 365 or 366549*/550public int length() {551return isLeap() ? 366 : 365;552}553554//-----------------------------------------------------------------------555/**556* Returns an adjusted copy of this year.557* <p>558* This returns a {@code Year}, based on this one, with the year adjusted.559* The adjustment takes place using the specified adjuster strategy object.560* Read the documentation of the adjuster to understand what adjustment will be made.561* <p>562* The result of this method is obtained by invoking the563* {@link TemporalAdjuster#adjustInto(Temporal)} method on the564* specified adjuster passing {@code this} as the argument.565* <p>566* This instance is immutable and unaffected by this method call.567*568* @param adjuster the adjuster to use, not null569* @return a {@code Year} based on {@code this} with the adjustment made, not null570* @throws DateTimeException if the adjustment cannot be made571* @throws ArithmeticException if numeric overflow occurs572*/573@Override574public Year with(TemporalAdjuster adjuster) {575return (Year) adjuster.adjustInto(this);576}577578/**579* Returns a copy of this year with the specified field set to a new value.580* <p>581* This returns a {@code Year}, based on this one, with the value582* for the specified field changed.583* If it is not possible to set the value, because the field is not supported or for584* some other reason, an exception is thrown.585* <p>586* If the field is a {@link ChronoField} then the adjustment is implemented here.587* The supported fields behave as follows:588* <ul>589* <li>{@code YEAR_OF_ERA} -590* Returns a {@code Year} with the specified year-of-era591* The era will be unchanged.592* <li>{@code YEAR} -593* Returns a {@code Year} with the specified year.594* This completely replaces the date and is equivalent to {@link #of(int)}.595* <li>{@code ERA} -596* Returns a {@code Year} with the specified era.597* The year-of-era will be unchanged.598* </ul>599* <p>600* In all cases, if the new value is outside the valid range of values for the field601* then a {@code DateTimeException} will be thrown.602* <p>603* All other {@code ChronoField} instances will throw an {@code UnsupportedTemporalTypeException}.604* <p>605* If the field is not a {@code ChronoField}, then the result of this method606* is obtained by invoking {@code TemporalField.adjustInto(Temporal, long)}607* passing {@code this} as the argument. In this case, the field determines608* whether and how to adjust the instant.609* <p>610* This instance is immutable and unaffected by this method call.611*612* @param field the field to set in the result, not null613* @param newValue the new value of the field in the result614* @return a {@code Year} based on {@code this} with the specified field set, not null615* @throws DateTimeException if the field cannot be set616* @throws UnsupportedTemporalTypeException if the field is not supported617* @throws ArithmeticException if numeric overflow occurs618*/619@Override620public Year with(TemporalField field, long newValue) {621if (field instanceof ChronoField chronoField) {622chronoField.checkValidValue(newValue);623switch (chronoField) {624case YEAR_OF_ERA: return Year.of((int) (year < 1 ? 1 - newValue : newValue));625case YEAR: return Year.of((int) newValue);626case ERA: return (getLong(ERA) == newValue ? this : Year.of(1 - year));627}628throw new UnsupportedTemporalTypeException("Unsupported field: " + field);629}630return field.adjustInto(this, newValue);631}632633//-----------------------------------------------------------------------634/**635* Returns a copy of this year with the specified amount added.636* <p>637* This returns a {@code Year}, based on this one, with the specified amount added.638* The amount is typically {@link Period} but may be any other type implementing639* the {@link TemporalAmount} interface.640* <p>641* The calculation is delegated to the amount object by calling642* {@link TemporalAmount#addTo(Temporal)}. The amount implementation is free643* to implement the addition in any way it wishes, however it typically644* calls back to {@link #plus(long, TemporalUnit)}. Consult the documentation645* of the amount implementation to determine if it can be successfully added.646* <p>647* This instance is immutable and unaffected by this method call.648*649* @param amountToAdd the amount to add, not null650* @return a {@code Year} based on this year with the addition made, not null651* @throws DateTimeException if the addition cannot be made652* @throws ArithmeticException if numeric overflow occurs653*/654@Override655public Year plus(TemporalAmount amountToAdd) {656return (Year) amountToAdd.addTo(this);657}658659/**660* Returns a copy of this year with the specified amount added.661* <p>662* This returns a {@code Year}, based on this one, with the amount663* in terms of the unit added. If it is not possible to add the amount, because the664* unit is not supported or for some other reason, an exception is thrown.665* <p>666* If the field is a {@link ChronoUnit} then the addition is implemented here.667* The supported fields behave as follows:668* <ul>669* <li>{@code YEARS} -670* Returns a {@code Year} with the specified number of years added.671* This is equivalent to {@link #plusYears(long)}.672* <li>{@code DECADES} -673* Returns a {@code Year} with the specified number of decades added.674* This is equivalent to calling {@link #plusYears(long)} with the amount675* multiplied by 10.676* <li>{@code CENTURIES} -677* Returns a {@code Year} with the specified number of centuries added.678* This is equivalent to calling {@link #plusYears(long)} with the amount679* multiplied by 100.680* <li>{@code MILLENNIA} -681* Returns a {@code Year} with the specified number of millennia added.682* This is equivalent to calling {@link #plusYears(long)} with the amount683* multiplied by 1,000.684* <li>{@code ERAS} -685* Returns a {@code Year} with the specified number of eras added.686* Only two eras are supported so the amount must be one, zero or minus one.687* If the amount is non-zero then the year is changed such that the year-of-era688* is unchanged.689* </ul>690* <p>691* All other {@code ChronoUnit} instances will throw an {@code UnsupportedTemporalTypeException}.692* <p>693* If the field is not a {@code ChronoUnit}, then the result of this method694* is obtained by invoking {@code TemporalUnit.addTo(Temporal, long)}695* passing {@code this} as the argument. In this case, the unit determines696* whether and how to perform the addition.697* <p>698* This instance is immutable and unaffected by this method call.699*700* @param amountToAdd the amount of the unit to add to the result, may be negative701* @param unit the unit of the amount to add, not null702* @return a {@code Year} based on this year with the specified amount added, not null703* @throws DateTimeException if the addition cannot be made704* @throws UnsupportedTemporalTypeException if the unit is not supported705* @throws ArithmeticException if numeric overflow occurs706*/707@Override708public Year plus(long amountToAdd, TemporalUnit unit) {709if (unit instanceof ChronoUnit chronoUnit) {710switch (chronoUnit) {711case YEARS: return plusYears(amountToAdd);712case DECADES: return plusYears(Math.multiplyExact(amountToAdd, 10));713case CENTURIES: return plusYears(Math.multiplyExact(amountToAdd, 100));714case MILLENNIA: return plusYears(Math.multiplyExact(amountToAdd, 1000));715case ERAS: return with(ERA, Math.addExact(getLong(ERA), amountToAdd));716}717throw new UnsupportedTemporalTypeException("Unsupported unit: " + unit);718}719return unit.addTo(this, amountToAdd);720}721722/**723* Returns a copy of this {@code Year} with the specified number of years added.724* <p>725* This instance is immutable and unaffected by this method call.726*727* @param yearsToAdd the years to add, may be negative728* @return a {@code Year} based on this year with the years added, not null729* @throws DateTimeException if the result exceeds the supported range730*/731public Year plusYears(long yearsToAdd) {732if (yearsToAdd == 0) {733return this;734}735return of(YEAR.checkValidIntValue(year + yearsToAdd)); // overflow safe736}737738//-----------------------------------------------------------------------739/**740* Returns a copy of this year with the specified amount subtracted.741* <p>742* This returns a {@code Year}, based on this one, with the specified amount subtracted.743* The amount is typically {@link Period} but may be any other type implementing744* the {@link TemporalAmount} interface.745* <p>746* The calculation is delegated to the amount object by calling747* {@link TemporalAmount#subtractFrom(Temporal)}. The amount implementation is free748* to implement the subtraction in any way it wishes, however it typically749* calls back to {@link #minus(long, TemporalUnit)}. Consult the documentation750* of the amount implementation to determine if it can be successfully subtracted.751* <p>752* This instance is immutable and unaffected by this method call.753*754* @param amountToSubtract the amount to subtract, not null755* @return a {@code Year} based on this year with the subtraction made, not null756* @throws DateTimeException if the subtraction cannot be made757* @throws ArithmeticException if numeric overflow occurs758*/759@Override760public Year minus(TemporalAmount amountToSubtract) {761return (Year) amountToSubtract.subtractFrom(this);762}763764/**765* Returns a copy of this year with the specified amount subtracted.766* <p>767* This returns a {@code Year}, based on this one, with the amount768* in terms of the unit subtracted. If it is not possible to subtract the amount,769* because the unit is not supported or for some other reason, an exception is thrown.770* <p>771* This method is equivalent to {@link #plus(long, TemporalUnit)} with the amount negated.772* See that method for a full description of how addition, and thus subtraction, works.773* <p>774* This instance is immutable and unaffected by this method call.775*776* @param amountToSubtract the amount of the unit to subtract from the result, may be negative777* @param unit the unit of the amount to subtract, not null778* @return a {@code Year} based on this year with the specified amount subtracted, not null779* @throws DateTimeException if the subtraction cannot be made780* @throws UnsupportedTemporalTypeException if the unit is not supported781* @throws ArithmeticException if numeric overflow occurs782*/783@Override784public Year minus(long amountToSubtract, TemporalUnit unit) {785return (amountToSubtract == Long.MIN_VALUE ? plus(Long.MAX_VALUE, unit).plus(1, unit) : plus(-amountToSubtract, unit));786}787788/**789* Returns a copy of this {@code Year} with the specified number of years subtracted.790* <p>791* This instance is immutable and unaffected by this method call.792*793* @param yearsToSubtract the years to subtract, may be negative794* @return a {@code Year} based on this year with the year subtracted, not null795* @throws DateTimeException if the result exceeds the supported range796*/797public Year minusYears(long yearsToSubtract) {798return (yearsToSubtract == Long.MIN_VALUE ? plusYears(Long.MAX_VALUE).plusYears(1) : plusYears(-yearsToSubtract));799}800801//-----------------------------------------------------------------------802/**803* Queries this year using the specified query.804* <p>805* This queries this year using the specified query strategy object.806* The {@code TemporalQuery} object defines the logic to be used to807* obtain the result. Read the documentation of the query to understand808* what the result of this method will be.809* <p>810* The result of this method is obtained by invoking the811* {@link TemporalQuery#queryFrom(TemporalAccessor)} method on the812* specified query passing {@code this} as the argument.813*814* @param <R> the type of the result815* @param query the query to invoke, not null816* @return the query result, null may be returned (defined by the query)817* @throws DateTimeException if unable to query (defined by the query)818* @throws ArithmeticException if numeric overflow occurs (defined by the query)819*/820@SuppressWarnings("unchecked")821@Override822public <R> R query(TemporalQuery<R> query) {823if (query == TemporalQueries.chronology()) {824return (R) IsoChronology.INSTANCE;825} else if (query == TemporalQueries.precision()) {826return (R) YEARS;827}828return Temporal.super.query(query);829}830831/**832* Adjusts the specified temporal object to have this year.833* <p>834* This returns a temporal object of the same observable type as the input835* with the year changed to be the same as this.836* <p>837* The adjustment is equivalent to using {@link Temporal#with(TemporalField, long)}838* passing {@link ChronoField#YEAR} as the field.839* If the specified temporal object does not use the ISO calendar system then840* a {@code DateTimeException} is thrown.841* <p>842* In most cases, it is clearer to reverse the calling pattern by using843* {@link Temporal#with(TemporalAdjuster)}:844* <pre>845* // these two lines are equivalent, but the second approach is recommended846* temporal = thisYear.adjustInto(temporal);847* temporal = temporal.with(thisYear);848* </pre>849* <p>850* This instance is immutable and unaffected by this method call.851*852* @param temporal the target object to be adjusted, not null853* @return the adjusted object, not null854* @throws DateTimeException if unable to make the adjustment855* @throws ArithmeticException if numeric overflow occurs856*/857@Override858public Temporal adjustInto(Temporal temporal) {859if (Chronology.from(temporal).equals(IsoChronology.INSTANCE) == false) {860throw new DateTimeException("Adjustment only supported on ISO date-time");861}862return temporal.with(YEAR, year);863}864865/**866* Calculates the amount of time until another year in terms of the specified unit.867* <p>868* This calculates the amount of time between two {@code Year}869* objects in terms of a single {@code TemporalUnit}.870* The start and end points are {@code this} and the specified year.871* The result will be negative if the end is before the start.872* The {@code Temporal} passed to this method is converted to a873* {@code Year} using {@link #from(TemporalAccessor)}.874* For example, the amount in decades between two year can be calculated875* using {@code startYear.until(endYear, DECADES)}.876* <p>877* The calculation returns a whole number, representing the number of878* complete units between the two years.879* For example, the amount in decades between 2012 and 2031880* will only be one decade as it is one year short of two decades.881* <p>882* There are two equivalent ways of using this method.883* The first is to invoke this method.884* The second is to use {@link TemporalUnit#between(Temporal, Temporal)}:885* <pre>886* // these two lines are equivalent887* amount = start.until(end, YEARS);888* amount = YEARS.between(start, end);889* </pre>890* The choice should be made based on which makes the code more readable.891* <p>892* The calculation is implemented in this method for {@link ChronoUnit}.893* The units {@code YEARS}, {@code DECADES}, {@code CENTURIES},894* {@code MILLENNIA} and {@code ERAS} are supported.895* Other {@code ChronoUnit} values will throw an exception.896* <p>897* If the unit is not a {@code ChronoUnit}, then the result of this method898* is obtained by invoking {@code TemporalUnit.between(Temporal, Temporal)}899* passing {@code this} as the first argument and the converted input temporal900* as the second argument.901* <p>902* This instance is immutable and unaffected by this method call.903*904* @param endExclusive the end date, exclusive, which is converted to a {@code Year}, not null905* @param unit the unit to measure the amount in, not null906* @return the amount of time between this year and the end year907* @throws DateTimeException if the amount cannot be calculated, or the end908* temporal cannot be converted to a {@code Year}909* @throws UnsupportedTemporalTypeException if the unit is not supported910* @throws ArithmeticException if numeric overflow occurs911*/912@Override913public long until(Temporal endExclusive, TemporalUnit unit) {914Year end = Year.from(endExclusive);915if (unit instanceof ChronoUnit chronoUnit) {916long yearsUntil = ((long) end.year) - year; // no overflow917switch (chronoUnit) {918case YEARS: return yearsUntil;919case DECADES: return yearsUntil / 10;920case CENTURIES: return yearsUntil / 100;921case MILLENNIA: return yearsUntil / 1000;922case ERAS: return end.getLong(ERA) - getLong(ERA);923}924throw new UnsupportedTemporalTypeException("Unsupported unit: " + unit);925}926return unit.between(this, end);927}928929/**930* Formats this year using the specified formatter.931* <p>932* This year will be passed to the formatter to produce a string.933*934* @param formatter the formatter to use, not null935* @return the formatted year string, not null936* @throws DateTimeException if an error occurs during printing937*/938public String format(DateTimeFormatter formatter) {939Objects.requireNonNull(formatter, "formatter");940return formatter.format(this);941}942943//-----------------------------------------------------------------------944/**945* Combines this year with a day-of-year to create a {@code LocalDate}.946* <p>947* This returns a {@code LocalDate} formed from this year and the specified day-of-year.948* <p>949* The day-of-year value 366 is only valid in a leap year.950*951* @param dayOfYear the day-of-year to use, from 1 to 365-366952* @return the local date formed from this year and the specified date of year, not null953* @throws DateTimeException if the day of year is zero or less, 366 or greater or equal954* to 366 and this is not a leap year955*/956public LocalDate atDay(int dayOfYear) {957return LocalDate.ofYearDay(year, dayOfYear);958}959960/**961* Combines this year with a month to create a {@code YearMonth}.962* <p>963* This returns a {@code YearMonth} formed from this year and the specified month.964* All possible combinations of year and month are valid.965* <p>966* This method can be used as part of a chain to produce a date:967* <pre>968* LocalDate date = year.atMonth(month).atDay(day);969* </pre>970*971* @param month the month-of-year to use, not null972* @return the year-month formed from this year and the specified month, not null973*/974public YearMonth atMonth(Month month) {975return YearMonth.of(year, month);976}977978/**979* Combines this year with a month to create a {@code YearMonth}.980* <p>981* This returns a {@code YearMonth} formed from this year and the specified month.982* All possible combinations of year and month are valid.983* <p>984* This method can be used as part of a chain to produce a date:985* <pre>986* LocalDate date = year.atMonth(month).atDay(day);987* </pre>988*989* @param month the month-of-year to use, from 1 (January) to 12 (December)990* @return the year-month formed from this year and the specified month, not null991* @throws DateTimeException if the month is invalid992*/993public YearMonth atMonth(int month) {994return YearMonth.of(year, month);995}996997/**998* Combines this year with a month-day to create a {@code LocalDate}.999* <p>1000* This returns a {@code LocalDate} formed from this year and the specified month-day.1001* <p>1002* A month-day of February 29th will be adjusted to February 28th in the resulting1003* date if the year is not a leap year.1004*1005* @param monthDay the month-day to use, not null1006* @return the local date formed from this year and the specified month-day, not null1007*/1008public LocalDate atMonthDay(MonthDay monthDay) {1009return monthDay.atYear(year);1010}10111012//-----------------------------------------------------------------------1013/**1014* Compares this year to another year.1015* <p>1016* The comparison is based on the value of the year.1017* It is "consistent with equals", as defined by {@link Comparable}.1018*1019* @param other the other year to compare to, not null1020* @return the comparator value, negative if less, positive if greater1021*/1022@Override1023public int compareTo(Year other) {1024return year - other.year;1025}10261027/**1028* Checks if this year is after the specified year.1029*1030* @param other the other year to compare to, not null1031* @return true if this is after the specified year1032*/1033public boolean isAfter(Year other) {1034return year > other.year;1035}10361037/**1038* Checks if this year is before the specified year.1039*1040* @param other the other year to compare to, not null1041* @return true if this point is before the specified year1042*/1043public boolean isBefore(Year other) {1044return year < other.year;1045}10461047//-----------------------------------------------------------------------1048/**1049* Checks if this year is equal to another year.1050* <p>1051* The comparison is based on the time-line position of the years.1052*1053* @param obj the object to check, null returns false1054* @return true if this is equal to the other year1055*/1056@Override1057public boolean equals(Object obj) {1058if (this == obj) {1059return true;1060}1061if (obj instanceof Year) {1062return year == ((Year) obj).year;1063}1064return false;1065}10661067/**1068* A hash code for this year.1069*1070* @return a suitable hash code1071*/1072@Override1073public int hashCode() {1074return year;1075}10761077//-----------------------------------------------------------------------1078/**1079* Outputs this year as a {@code String}.1080*1081* @return a string representation of this year, not null1082*/1083@Override1084public String toString() {1085return Integer.toString(year);1086}10871088//-----------------------------------------------------------------------1089/**1090* Writes the object using a1091* <a href="{@docRoot}/serialized-form.html#java.time.Ser">dedicated serialized form</a>.1092* @serialData1093* <pre>1094* out.writeByte(11); // identifies a Year1095* out.writeInt(year);1096* </pre>1097*1098* @return the instance of {@code Ser}, not null1099*/1100@java.io.Serial1101private Object writeReplace() {1102return new Ser(Ser.YEAR_TYPE, this);1103}11041105/**1106* Defend against malicious streams.1107*1108* @param s the stream to read1109* @throws InvalidObjectException always1110*/1111@java.io.Serial1112private void readObject(ObjectInputStream s) throws InvalidObjectException {1113throw new InvalidObjectException("Deserialization via serialization delegate");1114}11151116void writeExternal(DataOutput out) throws IOException {1117out.writeInt(year);1118}11191120static Year readExternal(DataInput in) throws IOException {1121return Year.of(in.readInt());1122}11231124}112511261127