Path: blob/master/src/java.base/share/classes/java/time/chrono/ChronoPeriod.java
41159 views
/*1* Copyright (c) 2013, 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) 2013, 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.chrono;6263import java.time.DateTimeException;64import java.time.temporal.ChronoUnit;65import java.time.temporal.Temporal;66import java.time.temporal.TemporalAmount;67import java.time.temporal.TemporalUnit;68import java.time.temporal.UnsupportedTemporalTypeException;69import java.util.List;70import java.util.Objects;7172/**73* A date-based amount of time, such as '3 years, 4 months and 5 days' in an74* arbitrary chronology, intended for advanced globalization use cases.75* <p>76* This interface models a date-based amount of time in a calendar system.77* While most calendar systems use years, months and days, some do not.78* Therefore, this interface operates solely in terms of a set of supported79* units that are defined by the {@code Chronology}.80* The set of supported units is fixed for a given chronology.81* The amount of a supported unit may be set to zero.82* <p>83* The period is modeled as a directed amount of time, meaning that individual84* parts of the period may be negative.85*86* @implSpec87* This interface must be implemented with care to ensure other classes operate correctly.88* All implementations that can be instantiated must be final, immutable and thread-safe.89* Subclasses should be Serializable wherever possible.90*91* @since 1.892*/93public interface ChronoPeriod94extends TemporalAmount {9596/**97* Obtains a {@code ChronoPeriod} consisting of amount of time between two dates.98* <p>99* The start date is included, but the end date is not.100* The period is calculated using {@link ChronoLocalDate#until(ChronoLocalDate)}.101* As such, the calculation is chronology specific.102* <p>103* The chronology of the first date is used.104* The chronology of the second date is ignored, with the date being converted105* to the target chronology system before the calculation starts.106* <p>107* The result of this method can be a negative period if the end is before the start.108* In most cases, the positive/negative sign will be the same in each of the supported fields.109*110* @param startDateInclusive the start date, inclusive, specifying the chronology of the calculation, not null111* @param endDateExclusive the end date, exclusive, in any chronology, not null112* @return the period between this date and the end date, not null113* @see ChronoLocalDate#until(ChronoLocalDate)114*/115public static ChronoPeriod between(ChronoLocalDate startDateInclusive, ChronoLocalDate endDateExclusive) {116Objects.requireNonNull(startDateInclusive, "startDateInclusive");117Objects.requireNonNull(endDateExclusive, "endDateExclusive");118return startDateInclusive.until(endDateExclusive);119}120121//-----------------------------------------------------------------------122/**123* Gets the value of the requested unit.124* <p>125* The supported units are chronology specific.126* They will typically be {@link ChronoUnit#YEARS YEARS},127* {@link ChronoUnit#MONTHS MONTHS} and {@link ChronoUnit#DAYS DAYS}.128* Requesting an unsupported unit will throw an exception.129*130* @param unit the {@code TemporalUnit} for which to return the value131* @return the long value of the unit132* @throws DateTimeException if the unit is not supported133* @throws UnsupportedTemporalTypeException if the unit is not supported134*/135@Override136long get(TemporalUnit unit);137138/**139* Gets the set of units supported by this period.140* <p>141* The supported units are chronology specific.142* They will typically be {@link ChronoUnit#YEARS YEARS},143* {@link ChronoUnit#MONTHS MONTHS} and {@link ChronoUnit#DAYS DAYS}.144* They are returned in order from largest to smallest.145* <p>146* This set can be used in conjunction with {@link #get(TemporalUnit)}147* to access the entire state of the period.148*149* @return a list containing the supported units, not null150*/151@Override152List<TemporalUnit> getUnits();153154/**155* Gets the chronology that defines the meaning of the supported units.156* <p>157* The period is defined by the chronology.158* It controls the supported units and restricts addition/subtraction159* to {@code ChronoLocalDate} instances of the same chronology.160*161* @return the chronology defining the period, not null162*/163Chronology getChronology();164165//-----------------------------------------------------------------------166/**167* Checks if all the supported units of this period are zero.168*169* @return true if this period is zero-length170*/171default boolean isZero() {172for (TemporalUnit unit : getUnits()) {173if (get(unit) != 0) {174return false;175}176}177return true;178}179180/**181* Checks if any of the supported units of this period are negative.182*183* @return true if any unit of this period is negative184*/185default boolean isNegative() {186for (TemporalUnit unit : getUnits()) {187if (get(unit) < 0) {188return true;189}190}191return false;192}193194//-----------------------------------------------------------------------195/**196* Returns a copy of this period with the specified period added.197* <p>198* If the specified amount is a {@code ChronoPeriod} then it must have199* the same chronology as this period. Implementations may choose to200* accept or reject other {@code TemporalAmount} implementations.201* <p>202* This instance is immutable and unaffected by this method call.203*204* @param amountToAdd the period to add, not null205* @return a {@code ChronoPeriod} based on this period with the requested period added, not null206* @throws ArithmeticException if numeric overflow occurs207*/208ChronoPeriod plus(TemporalAmount amountToAdd);209210/**211* Returns a copy of this period with the specified period subtracted.212* <p>213* If the specified amount is a {@code ChronoPeriod} then it must have214* the same chronology as this period. Implementations may choose to215* accept or reject other {@code TemporalAmount} implementations.216* <p>217* This instance is immutable and unaffected by this method call.218*219* @param amountToSubtract the period to subtract, not null220* @return a {@code ChronoPeriod} based on this period with the requested period subtracted, not null221* @throws ArithmeticException if numeric overflow occurs222*/223ChronoPeriod minus(TemporalAmount amountToSubtract);224225//-----------------------------------------------------------------------226/**227* Returns a new instance with each amount in this period in this period228* multiplied by the specified scalar.229* <p>230* This returns a period with each supported unit individually multiplied.231* For example, a period of "2 years, -3 months and 4 days" multiplied by232* 3 will return "6 years, -9 months and 12 days".233* No normalization is performed.234*235* @param scalar the scalar to multiply by, not null236* @return a {@code ChronoPeriod} based on this period with the amounts multiplied237* by the scalar, not null238* @throws ArithmeticException if numeric overflow occurs239*/240ChronoPeriod multipliedBy(int scalar);241242/**243* Returns a new instance with each amount in this period negated.244* <p>245* This returns a period with each supported unit individually negated.246* For example, a period of "2 years, -3 months and 4 days" will be247* negated to "-2 years, 3 months and -4 days".248* No normalization is performed.249*250* @return a {@code ChronoPeriod} based on this period with the amounts negated, not null251* @throws ArithmeticException if numeric overflow occurs, which only happens if252* one of the units has the value {@code Long.MIN_VALUE}253*/254default ChronoPeriod negated() {255return multipliedBy(-1);256}257258//-----------------------------------------------------------------------259/**260* Returns a copy of this period with the amounts of each unit normalized.261* <p>262* The process of normalization is specific to each calendar system.263* For example, in the ISO calendar system, the years and months are264* normalized but the days are not, such that "15 months" would be265* normalized to "1 year and 3 months".266* <p>267* This instance is immutable and unaffected by this method call.268*269* @return a {@code ChronoPeriod} based on this period with the amounts of each270* unit normalized, not null271* @throws ArithmeticException if numeric overflow occurs272*/273ChronoPeriod normalized();274275//-------------------------------------------------------------------------276/**277* Adds this period to the specified temporal object.278* <p>279* This returns a temporal object of the same observable type as the input280* with this period added.281* <p>282* In most cases, it is clearer to reverse the calling pattern by using283* {@link Temporal#plus(TemporalAmount)}.284* <pre>285* // these two lines are equivalent, but the second approach is recommended286* dateTime = thisPeriod.addTo(dateTime);287* dateTime = dateTime.plus(thisPeriod);288* </pre>289* <p>290* The specified temporal must have the same chronology as this period.291* This returns a temporal with the non-zero supported units added.292* <p>293* This instance is immutable and unaffected by this method call.294*295* @param temporal the temporal object to adjust, not null296* @return an object of the same type with the adjustment made, not null297* @throws DateTimeException if unable to add298* @throws ArithmeticException if numeric overflow occurs299*/300@Override301Temporal addTo(Temporal temporal);302303/**304* Subtracts this period from the specified temporal object.305* <p>306* This returns a temporal object of the same observable type as the input307* with this period subtracted.308* <p>309* In most cases, it is clearer to reverse the calling pattern by using310* {@link Temporal#minus(TemporalAmount)}.311* <pre>312* // these two lines are equivalent, but the second approach is recommended313* dateTime = thisPeriod.subtractFrom(dateTime);314* dateTime = dateTime.minus(thisPeriod);315* </pre>316* <p>317* The specified temporal must have the same chronology as this period.318* This returns a temporal with the non-zero supported units subtracted.319* <p>320* This instance is immutable and unaffected by this method call.321*322* @param temporal the temporal object to adjust, not null323* @return an object of the same type with the adjustment made, not null324* @throws DateTimeException if unable to subtract325* @throws ArithmeticException if numeric overflow occurs326*/327@Override328Temporal subtractFrom(Temporal temporal);329330//-----------------------------------------------------------------------331/**332* Checks if this period is equal to another period, including the chronology.333* <p>334* Compares this period with another ensuring that the type, each amount and335* the chronology are the same.336* Note that this means that a period of "15 Months" is not equal to a period337* of "1 Year and 3 Months".338*339* @param obj the object to check, null returns false340* @return true if this is equal to the other period341*/342@Override343boolean equals(Object obj);344345/**346* A hash code for this period.347*348* @return a suitable hash code349*/350@Override351int hashCode();352353//-----------------------------------------------------------------------354/**355* Outputs this period as a {@code String}.356* <p>357* The output will include the period amounts and chronology.358*359* @return a string representation of this period, not null360*/361@Override362String toString();363364}365366367