Path: blob/master/src/java.base/share/classes/java/time/Period.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) 2008-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.ChronoUnit.DAYS;64import static java.time.temporal.ChronoUnit.MONTHS;65import static java.time.temporal.ChronoUnit.YEARS;6667import java.io.DataInput;68import java.io.DataOutput;69import java.io.IOException;70import java.io.InvalidObjectException;71import java.io.ObjectInputStream;72import java.io.Serializable;73import java.time.chrono.ChronoLocalDate;74import java.time.chrono.ChronoPeriod;75import java.time.chrono.Chronology;76import java.time.chrono.IsoChronology;77import java.time.format.DateTimeParseException;78import java.time.temporal.ChronoUnit;79import java.time.temporal.Temporal;80import java.time.temporal.TemporalAccessor;81import java.time.temporal.TemporalAmount;82import java.time.temporal.TemporalQueries;83import java.time.temporal.TemporalUnit;84import java.time.temporal.UnsupportedTemporalTypeException;85import java.util.List;86import java.util.Objects;87import java.util.regex.Matcher;88import java.util.regex.Pattern;8990/**91* A date-based amount of time in the ISO-8601 calendar system,92* such as '2 years, 3 months and 4 days'.93* <p>94* This class models a quantity or amount of time in terms of years, months and days.95* See {@link Duration} for the time-based equivalent to this class.96* <p>97* Durations and periods differ in their treatment of daylight savings time98* when added to {@link ZonedDateTime}. A {@code Duration} will add an exact99* number of seconds, thus a duration of one day is always exactly 24 hours.100* By contrast, a {@code Period} will add a conceptual day, trying to maintain101* the local time.102* <p>103* For example, consider adding a period of one day and a duration of one day to104* 18:00 on the evening before a daylight savings gap. The {@code Period} will add105* the conceptual day and result in a {@code ZonedDateTime} at 18:00 the following day.106* By contrast, the {@code Duration} will add exactly 24 hours, resulting in a107* {@code ZonedDateTime} at 19:00 the following day (assuming a one hour DST gap).108* <p>109* The supported units of a period are {@link ChronoUnit#YEARS YEARS},110* {@link ChronoUnit#MONTHS MONTHS} and {@link ChronoUnit#DAYS DAYS}.111* All three fields are always present, but may be set to zero.112* <p>113* The ISO-8601 calendar system is the modern civil calendar system used today114* in most of the world. It is equivalent to the proleptic Gregorian calendar115* system, in which today's rules for leap years are applied for all time.116* <p>117* The period is modeled as a directed amount of time, meaning that individual parts of the118* period may be negative.119* <p>120* This is a <a href="{@docRoot}/java.base/java/lang/doc-files/ValueBased.html">value-based</a>121* class; programmers should treat instances that are122* {@linkplain #equals(Object) equal} as interchangeable and should not123* use instances for synchronization, or unpredictable behavior may124* occur. For example, in a future release, synchronization may fail.125* The {@code equals} method should be used for comparisons.126*127* @implSpec128* This class is immutable and thread-safe.129*130* @since 1.8131*/132@jdk.internal.ValueBased133public final class Period134implements ChronoPeriod, Serializable {135136/**137* A constant for a period of zero.138*/139public static final Period ZERO = new Period(0, 0, 0);140/**141* Serialization version.142*/143@java.io.Serial144private static final long serialVersionUID = -3587258372562876L;145/**146* The pattern for parsing.147*/148private static final Pattern PATTERN =149Pattern.compile("([-+]?)P(?:([-+]?[0-9]+)Y)?(?:([-+]?[0-9]+)M)?(?:([-+]?[0-9]+)W)?(?:([-+]?[0-9]+)D)?", Pattern.CASE_INSENSITIVE);150151/**152* The set of supported units.153*/154private static final List<TemporalUnit> SUPPORTED_UNITS = List.of(YEARS, MONTHS, DAYS);155156/**157* The number of years.158*/159private final int years;160/**161* The number of months.162*/163private final int months;164/**165* The number of days.166*/167private final int days;168169//-----------------------------------------------------------------------170/**171* Obtains a {@code Period} representing a number of years.172* <p>173* The resulting period will have the specified years.174* The months and days units will be zero.175*176* @param years the number of years, positive or negative177* @return the period of years, not null178*/179public static Period ofYears(int years) {180return create(years, 0, 0);181}182183/**184* Obtains a {@code Period} representing a number of months.185* <p>186* The resulting period will have the specified months.187* The years and days units will be zero.188*189* @param months the number of months, positive or negative190* @return the period of months, not null191*/192public static Period ofMonths(int months) {193return create(0, months, 0);194}195196/**197* Obtains a {@code Period} representing a number of weeks.198* <p>199* The resulting period will be day-based, with the amount of days200* equal to the number of weeks multiplied by 7.201* The years and months units will be zero.202*203* @param weeks the number of weeks, positive or negative204* @return the period, with the input weeks converted to days, not null205*/206public static Period ofWeeks(int weeks) {207return create(0, 0, Math.multiplyExact(weeks, 7));208}209210/**211* Obtains a {@code Period} representing a number of days.212* <p>213* The resulting period will have the specified days.214* The years and months units will be zero.215*216* @param days the number of days, positive or negative217* @return the period of days, not null218*/219public static Period ofDays(int days) {220return create(0, 0, days);221}222223//-----------------------------------------------------------------------224/**225* Obtains a {@code Period} representing a number of years, months and days.226* <p>227* This creates an instance based on years, months and days.228*229* @param years the amount of years, may be negative230* @param months the amount of months, may be negative231* @param days the amount of days, may be negative232* @return the period of years, months and days, not null233*/234public static Period of(int years, int months, int days) {235return create(years, months, days);236}237238//-----------------------------------------------------------------------239/**240* Obtains an instance of {@code Period} from a temporal amount.241* <p>242* This obtains a period based on the specified amount.243* A {@code TemporalAmount} represents an amount of time, which may be244* date-based or time-based, which this factory extracts to a {@code Period}.245* <p>246* The conversion loops around the set of units from the amount and uses247* the {@link ChronoUnit#YEARS YEARS}, {@link ChronoUnit#MONTHS MONTHS}248* and {@link ChronoUnit#DAYS DAYS} units to create a period.249* If any other units are found then an exception is thrown.250* <p>251* If the amount is a {@code ChronoPeriod} then it must use the ISO chronology.252*253* @param amount the temporal amount to convert, not null254* @return the equivalent period, not null255* @throws DateTimeException if unable to convert to a {@code Period}256* @throws ArithmeticException if the amount of years, months or days exceeds an int257*/258public static Period from(TemporalAmount amount) {259if (amount instanceof Period) {260return (Period) amount;261}262if (amount instanceof ChronoPeriod) {263if (IsoChronology.INSTANCE.equals(((ChronoPeriod) amount).getChronology()) == false) {264throw new DateTimeException("Period requires ISO chronology: " + amount);265}266}267Objects.requireNonNull(amount, "amount");268int years = 0;269int months = 0;270int days = 0;271for (TemporalUnit unit : amount.getUnits()) {272long unitAmount = amount.get(unit);273if (unit == ChronoUnit.YEARS) {274years = Math.toIntExact(unitAmount);275} else if (unit == ChronoUnit.MONTHS) {276months = Math.toIntExact(unitAmount);277} else if (unit == ChronoUnit.DAYS) {278days = Math.toIntExact(unitAmount);279} else {280throw new DateTimeException("Unit must be Years, Months or Days, but was " + unit);281}282}283return create(years, months, days);284}285286//-----------------------------------------------------------------------287/**288* Obtains a {@code Period} from a text string such as {@code PnYnMnD}.289* <p>290* This will parse the string produced by {@code toString()} which is291* based on the ISO-8601 period formats {@code PnYnMnD} and {@code PnW}.292* <p>293* The string starts with an optional sign, denoted by the ASCII negative294* or positive symbol. If negative, the whole period is negated.295* The ASCII letter "P" is next in upper or lower case.296* There are then four sections, each consisting of a number and a suffix.297* At least one of the four sections must be present.298* The sections have suffixes in ASCII of "Y", "M", "W" and "D" for299* years, months, weeks and days, accepted in upper or lower case.300* The suffixes must occur in order.301* The number part of each section must consist of ASCII digits.302* The number may be prefixed by the ASCII negative or positive symbol.303* The number must parse to an {@code int}.304* <p>305* The leading plus/minus sign, and negative values for other units are306* not part of the ISO-8601 standard. In addition, ISO-8601 does not307* permit mixing between the {@code PnYnMnD} and {@code PnW} formats.308* Any week-based input is multiplied by 7 and treated as a number of days.309* <p>310* For example, the following are valid inputs:311* <pre>312* "P2Y" -- Period.ofYears(2)313* "P3M" -- Period.ofMonths(3)314* "P4W" -- Period.ofWeeks(4)315* "P5D" -- Period.ofDays(5)316* "P1Y2M3D" -- Period.of(1, 2, 3)317* "P1Y2M3W4D" -- Period.of(1, 2, 25)318* "P-1Y2M" -- Period.of(-1, 2, 0)319* "-P1Y2M" -- Period.of(-1, -2, 0)320* </pre>321*322* @param text the text to parse, not null323* @return the parsed period, not null324* @throws DateTimeParseException if the text cannot be parsed to a period325*/326public static Period parse(CharSequence text) {327Objects.requireNonNull(text, "text");328Matcher matcher = PATTERN.matcher(text);329if (matcher.matches()) {330int negate = (charMatch(text, matcher.start(1), matcher.end(1), '-') ? -1 : 1);331int yearStart = matcher.start(2), yearEnd = matcher.end(2);332int monthStart = matcher.start(3), monthEnd = matcher.end(3);333int weekStart = matcher.start(4), weekEnd = matcher.end(4);334int dayStart = matcher.start(5), dayEnd = matcher.end(5);335if (yearStart >= 0 || monthStart >= 0 || weekStart >= 0 || dayStart >= 0) {336try {337int years = parseNumber(text, yearStart, yearEnd, negate);338int months = parseNumber(text, monthStart, monthEnd, negate);339int weeks = parseNumber(text, weekStart, weekEnd, negate);340int days = parseNumber(text, dayStart, dayEnd, negate);341days = Math.addExact(days, Math.multiplyExact(weeks, 7));342return create(years, months, days);343} catch (NumberFormatException ex) {344throw new DateTimeParseException("Text cannot be parsed to a Period", text, 0, ex);345}346}347}348throw new DateTimeParseException("Text cannot be parsed to a Period", text, 0);349}350351private static boolean charMatch(CharSequence text, int start, int end, char c) {352return (start >= 0 && end == start + 1 && text.charAt(start) == c);353}354355private static int parseNumber(CharSequence text, int start, int end, int negate) {356if (start < 0 || end < 0) {357return 0;358}359int val = Integer.parseInt(text, start, end, 10);360try {361return Math.multiplyExact(val, negate);362} catch (ArithmeticException ex) {363throw new DateTimeParseException("Text cannot be parsed to a Period", text, 0, ex);364}365}366367//-----------------------------------------------------------------------368/**369* Obtains a {@code Period} consisting of the number of years, months,370* and days between two dates.371* <p>372* The start date is included, but the end date is not.373* The period is calculated by removing complete months, then calculating374* the remaining number of days, adjusting to ensure that both have the same sign.375* The number of months is then split into years and months based on a 12 month year.376* A month is considered if the end day-of-month is greater than or equal to the start day-of-month.377* For example, from {@code 2010-01-15} to {@code 2011-03-18} is one year, two months and three days.378* <p>379* The result of this method can be a negative period if the end is before the start.380* The negative sign will be the same in each of year, month and day.381*382* @param startDateInclusive the start date, inclusive, not null383* @param endDateExclusive the end date, exclusive, not null384* @return the period between this date and the end date, not null385* @see ChronoLocalDate#until(ChronoLocalDate)386*/387public static Period between(LocalDate startDateInclusive, LocalDate endDateExclusive) {388return startDateInclusive.until(endDateExclusive);389}390391//-----------------------------------------------------------------------392/**393* Creates an instance.394*395* @param years the amount396* @param months the amount397* @param days the amount398*/399private static Period create(int years, int months, int days) {400if ((years | months | days) == 0) {401return ZERO;402}403return new Period(years, months, days);404}405406/**407* Constructor.408*409* @param years the amount410* @param months the amount411* @param days the amount412*/413private Period(int years, int months, int days) {414this.years = years;415this.months = months;416this.days = days;417}418419//-----------------------------------------------------------------------420/**421* Gets the value of the requested unit.422* <p>423* This returns a value for each of the three supported units,424* {@link ChronoUnit#YEARS YEARS}, {@link ChronoUnit#MONTHS MONTHS} and425* {@link ChronoUnit#DAYS DAYS}.426* All other units throw an exception.427*428* @param unit the {@code TemporalUnit} for which to return the value429* @return the long value of the unit430* @throws DateTimeException if the unit is not supported431* @throws UnsupportedTemporalTypeException if the unit is not supported432*/433@Override434public long get(TemporalUnit unit) {435if (unit == ChronoUnit.YEARS) {436return getYears();437} else if (unit == ChronoUnit.MONTHS) {438return getMonths();439} else if (unit == ChronoUnit.DAYS) {440return getDays();441} else {442throw new UnsupportedTemporalTypeException("Unsupported unit: " + unit);443}444}445446/**447* Gets the set of units supported by this period.448* <p>449* The supported units are {@link ChronoUnit#YEARS YEARS},450* {@link ChronoUnit#MONTHS MONTHS} and {@link ChronoUnit#DAYS DAYS}.451* They are returned in the order years, months, days.452* <p>453* This set can be used in conjunction with {@link #get(TemporalUnit)}454* to access the entire state of the period.455*456* @return a list containing the years, months and days units, not null457*/458@Override459public List<TemporalUnit> getUnits() {460return SUPPORTED_UNITS;461}462463/**464* Gets the chronology of this period, which is the ISO calendar system.465* <p>466* The {@code Chronology} represents the calendar system in use.467* The ISO-8601 calendar system is the modern civil calendar system used today468* in most of the world. It is equivalent to the proleptic Gregorian calendar469* system, in which today's rules for leap years are applied for all time.470*471* @return the ISO chronology, not null472*/473@Override474public IsoChronology getChronology() {475return IsoChronology.INSTANCE;476}477478//-----------------------------------------------------------------------479/**480* Checks if all three units of this period are zero.481* <p>482* A zero period has the value zero for the years, months and days units.483*484* @return true if this period is zero-length485*/486public boolean isZero() {487return (this == ZERO);488}489490/**491* Checks if any of the three units of this period are negative.492* <p>493* This checks whether the years, months or days units are less than zero.494*495* @return true if any unit of this period is negative496*/497public boolean isNegative() {498return years < 0 || months < 0 || days < 0;499}500501//-----------------------------------------------------------------------502/**503* Gets the amount of years of this period.504* <p>505* This returns the years unit.506* <p>507* The months unit is not automatically normalized with the years unit.508* This means that a period of "15 months" is different to a period509* of "1 year and 3 months".510*511* @return the amount of years of this period, may be negative512*/513public int getYears() {514return years;515}516517/**518* Gets the amount of months of this period.519* <p>520* This returns the months unit.521* <p>522* The months unit is not automatically normalized with the years unit.523* This means that a period of "15 months" is different to a period524* of "1 year and 3 months".525*526* @return the amount of months of this period, may be negative527*/528public int getMonths() {529return months;530}531532/**533* Gets the amount of days of this period.534* <p>535* This returns the days unit.536*537* @return the amount of days of this period, may be negative538*/539public int getDays() {540return days;541}542543//-----------------------------------------------------------------------544/**545* Returns a copy of this period with the specified amount of years.546* <p>547* This sets the amount of the years unit in a copy of this period.548* The months and days units are unaffected.549* <p>550* The months unit is not automatically normalized with the years unit.551* This means that a period of "15 months" is different to a period552* of "1 year and 3 months".553* <p>554* This instance is immutable and unaffected by this method call.555*556* @param years the years to represent, may be negative557* @return a {@code Period} based on this period with the requested years, not null558*/559public Period withYears(int years) {560if (years == this.years) {561return this;562}563return create(years, months, days);564}565566/**567* Returns a copy of this period with the specified amount of months.568* <p>569* This sets the amount of the months unit in a copy of this period.570* The years and days units are unaffected.571* <p>572* The months unit is not automatically normalized with the years unit.573* This means that a period of "15 months" is different to a period574* of "1 year and 3 months".575* <p>576* This instance is immutable and unaffected by this method call.577*578* @param months the months to represent, may be negative579* @return a {@code Period} based on this period with the requested months, not null580*/581public Period withMonths(int months) {582if (months == this.months) {583return this;584}585return create(years, months, days);586}587588/**589* Returns a copy of this period with the specified amount of days.590* <p>591* This sets the amount of the days unit in a copy of this period.592* The years and months units are unaffected.593* <p>594* This instance is immutable and unaffected by this method call.595*596* @param days the days to represent, may be negative597* @return a {@code Period} based on this period with the requested days, not null598*/599public Period withDays(int days) {600if (days == this.days) {601return this;602}603return create(years, months, days);604}605606//-----------------------------------------------------------------------607/**608* Returns a copy of this period with the specified period added.609* <p>610* This operates separately on the years, months and days.611* No normalization is performed.612* <p>613* For example, "1 year, 6 months and 3 days" plus "2 years, 2 months and 2 days"614* returns "3 years, 8 months and 5 days".615* <p>616* The specified amount is typically an instance of {@code Period}.617* Other types are interpreted using {@link Period#from(TemporalAmount)}.618* <p>619* This instance is immutable and unaffected by this method call.620*621* @param amountToAdd the amount to add, not null622* @return a {@code Period} based on this period with the requested period added, not null623* @throws DateTimeException if the specified amount has a non-ISO chronology or624* contains an invalid unit625* @throws ArithmeticException if numeric overflow occurs626*/627public Period plus(TemporalAmount amountToAdd) {628Period isoAmount = Period.from(amountToAdd);629return create(630Math.addExact(years, isoAmount.years),631Math.addExact(months, isoAmount.months),632Math.addExact(days, isoAmount.days));633}634635/**636* Returns a copy of this period with the specified years added.637* <p>638* This adds the amount to the years unit in a copy of this period.639* The months and days units are unaffected.640* For example, "1 year, 6 months and 3 days" plus 2 years returns "3 years, 6 months and 3 days".641* <p>642* This instance is immutable and unaffected by this method call.643*644* @param yearsToAdd the years to add, positive or negative645* @return a {@code Period} based on this period with the specified years added, not null646* @throws ArithmeticException if numeric overflow occurs647*/648public Period plusYears(long yearsToAdd) {649if (yearsToAdd == 0) {650return this;651}652return create(Math.toIntExact(Math.addExact(years, yearsToAdd)), months, days);653}654655/**656* Returns a copy of this period with the specified months added.657* <p>658* This adds the amount to the months unit in a copy of this period.659* The years and days units are unaffected.660* For example, "1 year, 6 months and 3 days" plus 2 months returns "1 year, 8 months and 3 days".661* <p>662* This instance is immutable and unaffected by this method call.663*664* @param monthsToAdd the months to add, positive or negative665* @return a {@code Period} based on this period with the specified months added, not null666* @throws ArithmeticException if numeric overflow occurs667*/668public Period plusMonths(long monthsToAdd) {669if (monthsToAdd == 0) {670return this;671}672return create(years, Math.toIntExact(Math.addExact(months, monthsToAdd)), days);673}674675/**676* Returns a copy of this period with the specified days added.677* <p>678* This adds the amount to the days unit in a copy of this period.679* The years and months units are unaffected.680* For example, "1 year, 6 months and 3 days" plus 2 days returns "1 year, 6 months and 5 days".681* <p>682* This instance is immutable and unaffected by this method call.683*684* @param daysToAdd the days to add, positive or negative685* @return a {@code Period} based on this period with the specified days added, not null686* @throws ArithmeticException if numeric overflow occurs687*/688public Period plusDays(long daysToAdd) {689if (daysToAdd == 0) {690return this;691}692return create(years, months, Math.toIntExact(Math.addExact(days, daysToAdd)));693}694695//-----------------------------------------------------------------------696/**697* Returns a copy of this period with the specified period subtracted.698* <p>699* This operates separately on the years, months and days.700* No normalization is performed.701* <p>702* For example, "1 year, 6 months and 3 days" minus "2 years, 2 months and 2 days"703* returns "-1 years, 4 months and 1 day".704* <p>705* The specified amount is typically an instance of {@code Period}.706* Other types are interpreted using {@link Period#from(TemporalAmount)}.707* <p>708* This instance is immutable and unaffected by this method call.709*710* @param amountToSubtract the amount to subtract, not null711* @return a {@code Period} based on this period with the requested period subtracted, not null712* @throws DateTimeException if the specified amount has a non-ISO chronology or713* contains an invalid unit714* @throws ArithmeticException if numeric overflow occurs715*/716public Period minus(TemporalAmount amountToSubtract) {717Period isoAmount = Period.from(amountToSubtract);718return create(719Math.subtractExact(years, isoAmount.years),720Math.subtractExact(months, isoAmount.months),721Math.subtractExact(days, isoAmount.days));722}723724/**725* Returns a copy of this period with the specified years subtracted.726* <p>727* This subtracts the amount from the years unit in a copy of this period.728* The months and days units are unaffected.729* For example, "1 year, 6 months and 3 days" minus 2 years returns "-1 years, 6 months and 3 days".730* <p>731* This instance is immutable and unaffected by this method call.732*733* @param yearsToSubtract the years to subtract, positive or negative734* @return a {@code Period} based on this period with the specified years subtracted, not null735* @throws ArithmeticException if numeric overflow occurs736*/737public Period minusYears(long yearsToSubtract) {738return (yearsToSubtract == Long.MIN_VALUE ? plusYears(Long.MAX_VALUE).plusYears(1) : plusYears(-yearsToSubtract));739}740741/**742* Returns a copy of this period with the specified months subtracted.743* <p>744* This subtracts the amount from the months unit in a copy of this period.745* The years and days units are unaffected.746* For example, "1 year, 6 months and 3 days" minus 2 months returns "1 year, 4 months and 3 days".747* <p>748* This instance is immutable and unaffected by this method call.749*750* @param monthsToSubtract the years to subtract, positive or negative751* @return a {@code Period} based on this period with the specified months subtracted, not null752* @throws ArithmeticException if numeric overflow occurs753*/754public Period minusMonths(long monthsToSubtract) {755return (monthsToSubtract == Long.MIN_VALUE ? plusMonths(Long.MAX_VALUE).plusMonths(1) : plusMonths(-monthsToSubtract));756}757758/**759* Returns a copy of this period with the specified days subtracted.760* <p>761* This subtracts the amount from the days unit in a copy of this period.762* The years and months units are unaffected.763* For example, "1 year, 6 months and 3 days" minus 2 days returns "1 year, 6 months and 1 day".764* <p>765* This instance is immutable and unaffected by this method call.766*767* @param daysToSubtract the months to subtract, positive or negative768* @return a {@code Period} based on this period with the specified days subtracted, not null769* @throws ArithmeticException if numeric overflow occurs770*/771public Period minusDays(long daysToSubtract) {772return (daysToSubtract == Long.MIN_VALUE ? plusDays(Long.MAX_VALUE).plusDays(1) : plusDays(-daysToSubtract));773}774775//-----------------------------------------------------------------------776/**777* Returns a new instance with each element in this period multiplied778* by the specified scalar.779* <p>780* This returns a period with each of the years, months and days units781* individually multiplied.782* For example, a period of "2 years, -3 months and 4 days" multiplied by783* 3 will return "6 years, -9 months and 12 days".784* No normalization is performed.785*786* @param scalar the scalar to multiply by, not null787* @return a {@code Period} based on this period with the amounts multiplied by the scalar, not null788* @throws ArithmeticException if numeric overflow occurs789*/790public Period multipliedBy(int scalar) {791if (this == ZERO || scalar == 1) {792return this;793}794return create(795Math.multiplyExact(years, scalar),796Math.multiplyExact(months, scalar),797Math.multiplyExact(days, scalar));798}799800/**801* Returns a new instance with each amount in this period negated.802* <p>803* This returns a period with each of the years, months and days units804* individually negated.805* For example, a period of "2 years, -3 months and 4 days" will be806* negated to "-2 years, 3 months and -4 days".807* No normalization is performed.808*809* @return a {@code Period} based on this period with the amounts negated, not null810* @throws ArithmeticException if numeric overflow occurs, which only happens if811* one of the units has the value {@code Integer.MIN_VALUE}812*/813public Period negated() {814return multipliedBy(-1);815}816817//-----------------------------------------------------------------------818/**819* Returns a copy of this period with the years and months normalized.820* <p>821* This normalizes the years and months units, leaving the days unit unchanged.822* The months unit is adjusted to have an absolute value less than 12,823* with the years unit being adjusted to compensate. For example, a period of824* "1 Year and 15 months" will be normalized to "2 years and 3 months".825* <p>826* The sign of the years and months units will be the same after normalization.827* For example, a period of "1 year and -25 months" will be normalized to828* "-1 year and -1 month".829* <p>830* This instance is immutable and unaffected by this method call.831*832* @return a {@code Period} based on this period with excess months normalized to years, not null833* @throws ArithmeticException if numeric overflow occurs834*/835public Period normalized() {836long totalMonths = toTotalMonths();837long splitYears = totalMonths / 12;838int splitMonths = (int) (totalMonths % 12); // no overflow839if (splitYears == years && splitMonths == months) {840return this;841}842return create(Math.toIntExact(splitYears), splitMonths, days);843}844845/**846* Gets the total number of months in this period.847* <p>848* This returns the total number of months in the period by multiplying the849* number of years by 12 and adding the number of months.850* <p>851* This instance is immutable and unaffected by this method call.852*853* @return the total number of months in the period, may be negative854*/855public long toTotalMonths() {856return years * 12L + months; // no overflow857}858859//-------------------------------------------------------------------------860/**861* Adds this period to the specified temporal object.862* <p>863* This returns a temporal object of the same observable type as the input864* with this period added.865* If the temporal has a chronology, it must be the ISO chronology.866* <p>867* In most cases, it is clearer to reverse the calling pattern by using868* {@link Temporal#plus(TemporalAmount)}.869* <pre>870* // these two lines are equivalent, but the second approach is recommended871* dateTime = thisPeriod.addTo(dateTime);872* dateTime = dateTime.plus(thisPeriod);873* </pre>874* <p>875* The calculation operates as follows.876* First, the chronology of the temporal is checked to ensure it is ISO chronology or null.877* Second, if the months are zero, the years are added if non-zero, otherwise878* the combination of years and months is added if non-zero.879* Finally, any days are added.880* <p>881* This approach ensures that a partial period can be added to a partial date.882* For example, a period of years and/or months can be added to a {@code YearMonth},883* but a period including days cannot.884* The approach also adds years and months together when necessary, which ensures885* correct behaviour at the end of the month.886* <p>887* This instance is immutable and unaffected by this method call.888*889* @param temporal the temporal object to adjust, not null890* @return an object of the same type with the adjustment made, not null891* @throws DateTimeException if unable to add892* @throws ArithmeticException if numeric overflow occurs893*/894@Override895public Temporal addTo(Temporal temporal) {896validateChrono(temporal);897if (months == 0) {898if (years != 0) {899temporal = temporal.plus(years, YEARS);900}901} else {902long totalMonths = toTotalMonths();903if (totalMonths != 0) {904temporal = temporal.plus(totalMonths, MONTHS);905}906}907if (days != 0) {908temporal = temporal.plus(days, DAYS);909}910return temporal;911}912913/**914* Subtracts this period from the specified temporal object.915* <p>916* This returns a temporal object of the same observable type as the input917* with this period subtracted.918* If the temporal has a chronology, it must be the ISO chronology.919* <p>920* In most cases, it is clearer to reverse the calling pattern by using921* {@link Temporal#minus(TemporalAmount)}.922* <pre>923* // these two lines are equivalent, but the second approach is recommended924* dateTime = thisPeriod.subtractFrom(dateTime);925* dateTime = dateTime.minus(thisPeriod);926* </pre>927* <p>928* The calculation operates as follows.929* First, the chronology of the temporal is checked to ensure it is ISO chronology or null.930* Second, if the months are zero, the years are subtracted if non-zero, otherwise931* the combination of years and months is subtracted if non-zero.932* Finally, any days are subtracted.933* <p>934* This approach ensures that a partial period can be subtracted from a partial date.935* For example, a period of years and/or months can be subtracted from a {@code YearMonth},936* but a period including days cannot.937* The approach also subtracts years and months together when necessary, which ensures938* correct behaviour at the end of the month.939* <p>940* This instance is immutable and unaffected by this method call.941*942* @param temporal the temporal object to adjust, not null943* @return an object of the same type with the adjustment made, not null944* @throws DateTimeException if unable to subtract945* @throws ArithmeticException if numeric overflow occurs946*/947@Override948public Temporal subtractFrom(Temporal temporal) {949validateChrono(temporal);950if (months == 0) {951if (years != 0) {952temporal = temporal.minus(years, YEARS);953}954} else {955long totalMonths = toTotalMonths();956if (totalMonths != 0) {957temporal = temporal.minus(totalMonths, MONTHS);958}959}960if (days != 0) {961temporal = temporal.minus(days, DAYS);962}963return temporal;964}965966/**967* Validates that the temporal has the correct chronology.968*/969private void validateChrono(TemporalAccessor temporal) {970Objects.requireNonNull(temporal, "temporal");971Chronology temporalChrono = temporal.query(TemporalQueries.chronology());972if (temporalChrono != null && IsoChronology.INSTANCE.equals(temporalChrono) == false) {973throw new DateTimeException("Chronology mismatch, expected: ISO, actual: " + temporalChrono.getId());974}975}976977//-----------------------------------------------------------------------978/**979* Checks if this period is equal to another period.980* <p>981* The comparison is based on the type {@code Period} and each of the three amounts.982* To be equal, the years, months and days units must be individually equal.983* Note that this means that a period of "15 Months" is not equal to a period984* of "1 Year and 3 Months".985*986* @param obj the object to check, null returns false987* @return true if this is equal to the other period988*/989@Override990public boolean equals(Object obj) {991if (this == obj) {992return true;993}994return (obj instanceof Period other)995&& years == other.years996&& months == other.months997&& days == other.days;998}9991000/**1001* A hash code for this period.1002*1003* @return a suitable hash code1004*/1005@Override1006public int hashCode() {1007return years + Integer.rotateLeft(months, 8) + Integer.rotateLeft(days, 16);1008}10091010//-----------------------------------------------------------------------1011/**1012* Outputs this period as a {@code String}, such as {@code P6Y3M1D}.1013* <p>1014* The output will be in the ISO-8601 period format.1015* A zero period will be represented as zero days, 'P0D'.1016*1017* @return a string representation of this period, not null1018*/1019@Override1020public String toString() {1021if (this == ZERO) {1022return "P0D";1023} else {1024StringBuilder buf = new StringBuilder();1025buf.append('P');1026if (years != 0) {1027buf.append(years).append('Y');1028}1029if (months != 0) {1030buf.append(months).append('M');1031}1032if (days != 0) {1033buf.append(days).append('D');1034}1035return buf.toString();1036}1037}10381039//-----------------------------------------------------------------------1040/**1041* Writes the object using a1042* <a href="{@docRoot}/serialized-form.html#java.time.Ser">dedicated serialized form</a>.1043* @serialData1044* <pre>1045* out.writeByte(14); // identifies a Period1046* out.writeInt(years);1047* out.writeInt(months);1048* out.writeInt(days);1049* </pre>1050*1051* @return the instance of {@code Ser}, not null1052*/1053@java.io.Serial1054private Object writeReplace() {1055return new Ser(Ser.PERIOD_TYPE, this);1056}10571058/**1059* Defend against malicious streams.1060*1061* @param s the stream to read1062* @throws java.io.InvalidObjectException always1063*/1064@java.io.Serial1065private void readObject(ObjectInputStream s) throws InvalidObjectException {1066throw new InvalidObjectException("Deserialization via serialization delegate");1067}10681069void writeExternal(DataOutput out) throws IOException {1070out.writeInt(years);1071out.writeInt(months);1072out.writeInt(days);1073}10741075static Period readExternal(DataInput in) throws IOException {1076int years = in.readInt();1077int months = in.readInt();1078int days = in.readInt();1079return Period.of(years, months, days);1080}10811082}108310841085