diff --git a/jdk/src/share/classes/java/time/LocalDate.java b/jdk/src/share/classes/java/time/LocalDate.java index e2043f9a90d..110a80fc9c0 100644 --- a/jdk/src/share/classes/java/time/LocalDate.java +++ b/jdk/src/share/classes/java/time/LocalDate.java @@ -1642,12 +1642,12 @@ public final class LocalDate * * The choice should be made based on which makes the code more readable. * - * @param endDate the end date, exclusive, which may be in any chronology, not null + * @param endDateExclusive the end date, exclusive, which may be in any chronology, not null * @return the period between this date and the end date, not null */ @Override - public Period until(ChronoLocalDate endDate) { - LocalDate end = LocalDate.from(endDate); + public Period until(ChronoLocalDate endDateExclusive) { + LocalDate end = LocalDate.from(endDateExclusive); long totalMonths = end.getProlepticMonth() - this.getProlepticMonth(); // safe int days = end.day - this.day; if (totalMonths > 0 && days < 0) { diff --git a/jdk/src/share/classes/java/time/Period.java b/jdk/src/share/classes/java/time/Period.java index 161ce49e565..bd272a9913e 100644 --- a/jdk/src/share/classes/java/time/Period.java +++ b/jdk/src/share/classes/java/time/Period.java @@ -61,7 +61,6 @@ */ package java.time; -import static java.time.temporal.ChronoField.MONTH_OF_YEAR; import static java.time.temporal.ChronoUnit.DAYS; import static java.time.temporal.ChronoUnit.MONTHS; import static java.time.temporal.ChronoUnit.YEARS; @@ -70,17 +69,19 @@ import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import java.io.InvalidObjectException; -import java.io.InvalidObjectException; import java.io.Serializable; import java.time.chrono.ChronoLocalDate; +import java.time.chrono.ChronoPeriod; import java.time.chrono.Chronology; +import java.time.chrono.IsoChronology; import java.time.format.DateTimeParseException; import java.time.temporal.ChronoUnit; import java.time.temporal.Temporal; +import java.time.temporal.TemporalAccessor; import java.time.temporal.TemporalAmount; +import java.time.temporal.TemporalQuery; import java.time.temporal.TemporalUnit; import java.time.temporal.UnsupportedTemporalTypeException; -import java.time.temporal.ValueRange; import java.util.Arrays; import java.util.Collections; import java.util.List; @@ -89,12 +90,13 @@ import java.util.regex.Matcher; import java.util.regex.Pattern; /** - * A date-based amount of time, such as '2 years, 3 months and 4 days'. + * A date-based amount of time in the ISO-8601 calendar system, + * such as '2 years, 3 months and 4 days'. *
* This class models a quantity or amount of time in terms of years, months and days. * See {@link Duration} for the time-based equivalent to this class. *
- * Durations and period differ in their treatment of daylight savings time + * Durations and periods differ in their treatment of daylight savings time * when added to {@link ZonedDateTime}. A {@code Duration} will add an exact * number of seconds, thus a duration of one day is always exactly 24 hours. * By contrast, a {@code Period} will add a conceptual day, trying to maintain @@ -110,14 +112,12 @@ import java.util.regex.Pattern; * {@link ChronoUnit#MONTHS MONTHS} and {@link ChronoUnit#DAYS DAYS}. * All three fields are always present, but may be set to zero. *
- * The period may be used with any calendar system. - * The meaning of a "year" or "month" is only applied when the object is added to a date. + * The ISO-8601 calendar system is the modern civil calendar system used today + * in most of the world. It is equivalent to the proleptic Gregorian calendar + * system, in which today's rules for leap years are applied for all time. *
* The period is modeled as a directed amount of time, meaning that individual parts of the * period may be negative. - *
- * The months and years fields may be {@linkplain #normalized() normalized}. - * The normalization assumes a 12 month year, so is not appropriate for all calendar systems. * * @implSpec * This class is immutable and thread-safe. @@ -125,7 +125,7 @@ import java.util.regex.Pattern; * @since 1.8 */ public final class Period - implements TemporalAmount, Serializable { + implements ChronoPeriod, Serializable { /** * A constant for a period of zero. @@ -140,6 +140,7 @@ public final class Period */ private final static Pattern PATTERN = Pattern.compile("([-+]?)P(?:([-+]?[0-9]+)Y)?(?:([-+]?[0-9]+)M)?(?:([-+]?[0-9]+)W)?(?:([-+]?[0-9]+)D)?", Pattern.CASE_INSENSITIVE); + /** * The set of supported units. */ @@ -234,12 +235,14 @@ public final class Period *
* This obtains a period based on the specified amount. * A {@code TemporalAmount} represents an amount of time, which may be - * date-based or time-based, which this factory extracts to a period. + * date-based or time-based, which this factory extracts to a {@code Period}. *
* The conversion loops around the set of units from the amount and uses * the {@link ChronoUnit#YEARS YEARS}, {@link ChronoUnit#MONTHS MONTHS} * and {@link ChronoUnit#DAYS DAYS} units to create a period. * If any other units are found then an exception is thrown. + *
+ * If the amount is a {@code ChronoPeriod} then it must use the ISO chronology. * * @param amount the temporal amount to convert, not null * @return the equivalent period, not null @@ -247,6 +250,14 @@ public final class Period * @throws ArithmeticException if the amount of years, months or days exceeds an int */ public static Period from(TemporalAmount amount) { + if (amount instanceof Period) { + return (Period) amount; + } + if (amount instanceof ChronoPeriod) { + if (IsoChronology.INSTANCE.equals(((ChronoPeriod) amount).getChronology()) == false) { + throw new DateTimeException("Period requires ISO chronology: " + amount); + } + } Objects.requireNonNull(amount, "amount"); int years = 0; int months = 0; @@ -358,13 +369,13 @@ public final class Period * The result of this method can be a negative period if the end is before the start. * The negative sign will be the same in each of year, month and day. * - * @param startDate the start date, inclusive, not null - * @param endDate the end date, exclusive, not null + * @param startDateInclusive the start date, inclusive, not null + * @param endDateExclusive the end date, exclusive, not null * @return the period between this date and the end date, not null * @see ChronoLocalDate#until(ChronoLocalDate) */ - public static Period between(LocalDate startDate, LocalDate endDate) { - return startDate.until(endDate); + public static Period between(LocalDate startDateInclusive, LocalDate endDateExclusive) { + return startDateInclusive.until(endDateExclusive); } //----------------------------------------------------------------------- @@ -439,6 +450,21 @@ public final class Period return SUPPORTED_UNITS; } + /** + * Gets the chronology of this period, which is the ISO calendar system. + *
+ * The {@code Chronology} represents the calendar system in use. + * The ISO-8601 calendar system is the modern civil calendar system used today + * in most of the world. It is equivalent to the proleptic Gregorian calendar + * system, in which today's rules for leap years are applied for all time. + * + * @return the ISO chronology, not null + */ + @Override + public IsoChronology getChronology() { + return IsoChronology.INSTANCE; + } + //----------------------------------------------------------------------- /** * Checks if all three units of this period are zero. @@ -468,7 +494,7 @@ public final class Period *
* This returns the years unit. *
- * The months unit is not normalized with the years unit. + * The months unit is not automatically normalized with the years unit. * This means that a period of "15 months" is different to a period * of "1 year and 3 months". * @@ -483,7 +509,7 @@ public final class Period *
* This returns the months unit. *
- * The months unit is not normalized with the years unit. + * The months unit is not automatically normalized with the years unit. * This means that a period of "15 months" is different to a period * of "1 year and 3 months". * @@ -511,7 +537,7 @@ public final class Period * This sets the amount of the years unit in a copy of this period. * The months and days units are unaffected. *
- * The months unit is not normalized with the years unit. + * The months unit is not automatically normalized with the years unit. * This means that a period of "15 months" is different to a period * of "1 year and 3 months". *
@@ -533,7 +559,7 @@ public final class Period * This sets the amount of the months unit in a copy of this period. * The years and days units are unaffected. *
- * The months unit is not normalized with the years unit. + * The months unit is not automatically normalized with the years unit. * This means that a period of "15 months" is different to a period * of "1 year and 3 months". *
@@ -572,21 +598,28 @@ public final class Period * Returns a copy of this period with the specified period added. *
* This operates separately on the years, months and days. + * No normalization is performed. *
* For example, "1 year, 6 months and 3 days" plus "2 years, 2 months and 2 days" * returns "3 years, 8 months and 5 days". *
+ * The specified amount is typically an instance of {@code Period}. + * Other types are interpreted using {@link Period#from(TemporalAmount)}. + *
* This instance is immutable and unaffected by this method call. * * @param amountToAdd the period to add, not null * @return a {@code Period} based on this period with the requested period added, not null + * @throws DateTimeException if the specified amount has a non-ISO chronology or + * contains an invalid unit * @throws ArithmeticException if numeric overflow occurs */ - public Period plus(Period amountToAdd) { + public Period plus(TemporalAmount amountToAdd) { + Period isoAmount = Period.from(amountToAdd); return create( - Math.addExact(years, amountToAdd.years), - Math.addExact(months, amountToAdd.months), - Math.addExact(days, amountToAdd.days)); + Math.addExact(years, isoAmount.years), + Math.addExact(months, isoAmount.months), + Math.addExact(days, isoAmount.days)); } /** @@ -654,21 +687,28 @@ public final class Period * Returns a copy of this period with the specified period subtracted. *
* This operates separately on the years, months and days. + * No normalization is performed. *
* For example, "1 year, 6 months and 3 days" minus "2 years, 2 months and 2 days" * returns "-1 years, 4 months and 1 day". *
+ * The specified amount is typically an instance of {@code Period}. + * Other types are interpreted using {@link Period#from(TemporalAmount)}. + *
* This instance is immutable and unaffected by this method call. * * @param amountToSubtract the period to subtract, not null * @return a {@code Period} based on this period with the requested period subtracted, not null + * @throws DateTimeException if the specified amount has a non-ISO chronology or + * contains an invalid unit * @throws ArithmeticException if numeric overflow occurs */ - public Period minus(Period amountToSubtract) { + public Period minus(TemporalAmount amountToSubtract) { + Period isoAmount = Period.from(amountToSubtract); return create( - Math.subtractExact(years, amountToSubtract.years), - Math.subtractExact(months, amountToSubtract.months), - Math.subtractExact(days, amountToSubtract.days)); + Math.subtractExact(years, isoAmount.years), + Math.subtractExact(months, isoAmount.months), + Math.subtractExact(days, isoAmount.days)); } /** @@ -766,8 +806,7 @@ public final class Period //----------------------------------------------------------------------- /** - * Returns a copy of this period with the years and months normalized - * using a 12 month year. + * Returns a copy of this period with the years and months normalized. *
* This normalizes the years and months units, leaving the days unit unchanged. * The months unit is adjusted to have an absolute value less than 11, @@ -778,8 +817,6 @@ public final class Period * For example, a period of "1 year and -25 months" will be normalized to * "-1 year and -1 month". *
- * This normalization uses a 12 month year which is not valid for all calendar systems. - *
* This instance is immutable and unaffected by this method call. * * @return a {@code Period} based on this period with excess months normalized to years, not null @@ -796,13 +833,11 @@ public final class Period } /** - * Gets the total number of months in this period using a 12 month year. + * Gets the total number of months in this period. *
* This returns the total number of months in the period by multiplying the * number of years by 12 and adding the number of months. *
- * This uses a 12 month year which is not valid for all calendar systems. - *
* This instance is immutable and unaffected by this method call. * * @return the total number of months in the period, may be negative @@ -817,6 +852,7 @@ public final class Period *
* This returns a temporal object of the same observable type as the input * with this period added. + * If the temporal has a chronology, it must be the ISO chronology. *
* In most cases, it is clearer to reverse the calling pattern by using * {@link Temporal#plus(TemporalAmount)}. @@ -826,10 +862,17 @@ public final class Period * dateTime = dateTime.plus(thisPeriod); * *
- * The calculation will add the years, then months, then days. - * Only non-zero amounts will be added. - * If the date-time has a calendar system with a fixed number of months in a - * year, then the years and months will be combined before being added. + * The calculation operates as follows. + * First, the chronology of the temporal is checked to ensure it is ISO chronology or null. + * Second, if the months are zero, the years are added if non-zero, otherwise + * the combination of years and months is added if non-zero. + * Finally, any days are added. + *
+ * This approach ensures that a partial period can be added to a partial date. + * For example, a period of years and/or months can be added to a {@code YearMonth}, + * but a period including days cannot. + * The approach also adds years and months together when necessary, which ensures + * correct behaviour at the end of the month. *
* This instance is immutable and unaffected by this method call. * @@ -840,18 +883,15 @@ public final class Period */ @Override public Temporal addTo(Temporal temporal) { - Objects.requireNonNull(temporal, "temporal"); - if ((years | months) != 0) { - long monthRange = monthRange(temporal); - if (monthRange >= 0) { - temporal = temporal.plus(years * monthRange + months, MONTHS); - } else { - if (years != 0) { - temporal = temporal.plus(years, YEARS); - } - if (months != 0) { - temporal = temporal.plus(months, MONTHS); - } + validateChrono(temporal); + if (months == 0) { + if (years != 0) { + temporal = temporal.plus(years, YEARS); + } + } else { + long totalMonths = toTotalMonths(); + if (totalMonths != 0) { + temporal = temporal.plus(totalMonths, MONTHS); } } if (days != 0) { @@ -865,6 +905,7 @@ public final class Period *
* This returns a temporal object of the same observable type as the input * with this period subtracted. + * If the temporal has a chronology, it must be the ISO chronology. *
* In most cases, it is clearer to reverse the calling pattern by using * {@link Temporal#minus(TemporalAmount)}. @@ -874,10 +915,17 @@ public final class Period * dateTime = dateTime.minus(thisPeriod); * *
- * The calculation will subtract the years, then months, then days. - * Only non-zero amounts will be subtracted. - * If the date-time has a calendar system with a fixed number of months in a - * year, then the years and months will be combined before being subtracted. + * The calculation operates as follows. + * First, the chronology of the temporal is checked to ensure it is ISO chronology or null. + * Second, if the months are zero, the years are subtracted if non-zero, otherwise + * the combination of years and months is subtracted if non-zero. + * Finally, any days are subtracted. + *
+ * This approach ensures that a partial period can be subtracted from a partial date. + * For example, a period of years and/or months can be subtracted from a {@code YearMonth}, + * but a period including days cannot. + * The approach also subtracts years and months together when necessary, which ensures + * correct behaviour at the end of the month. *
* This instance is immutable and unaffected by this method call. * @@ -888,18 +936,15 @@ public final class Period */ @Override public Temporal subtractFrom(Temporal temporal) { - Objects.requireNonNull(temporal, "temporal"); - if ((years | months) != 0) { - long monthRange = monthRange(temporal); - if (monthRange >= 0) { - temporal = temporal.minus(years * monthRange + months, MONTHS); - } else { - if (years != 0) { - temporal = temporal.minus(years, YEARS); - } - if (months != 0) { - temporal = temporal.minus(months, MONTHS); - } + validateChrono(temporal); + if (months == 0) { + if (years != 0) { + temporal = temporal.minus(years, YEARS); + } + } else { + long totalMonths = toTotalMonths(); + if (totalMonths != 0) { + temporal = temporal.minus(totalMonths, MONTHS); } } if (days != 0) { @@ -909,26 +954,21 @@ public final class Period } /** - * Calculates the range of months based on the temporal. - * - * @param temporal the temporal, not null - * @return the month range, negative if not fixed range + * Validates that the temporal has the correct chronology. */ - private long monthRange(Temporal temporal) { - if (temporal.isSupported(MONTH_OF_YEAR)) { - ValueRange startRange = Chronology.from(temporal).range(MONTH_OF_YEAR); - if (startRange.isFixed() && startRange.isIntValue()) { - return startRange.getMaximum() - startRange.getMinimum() + 1; - } + private void validateChrono(TemporalAccessor temporal) { + Objects.requireNonNull(temporal, "temporal"); + Chronology temporalChrono = temporal.query(TemporalQuery.chronology()); + if (temporalChrono != null && IsoChronology.INSTANCE.equals(temporalChrono) == false) { + throw new DateTimeException("Chronology mismatch, expected: ISO, actual: " + temporalChrono.getId()); } - return -1; } //----------------------------------------------------------------------- /** * Checks if this period is equal to another period. *
- * The comparison is based on the amounts held in the period. + * The comparison is based on the type {@code Period} and each of the three amounts. * To be equal, the years, months and days units must be individually equal. * Note that this means that a period of "15 Months" is not equal to a period * of "1 Year and 3 Months". diff --git a/jdk/src/share/classes/java/time/chrono/ChronoLocalDate.java b/jdk/src/share/classes/java/time/chrono/ChronoLocalDate.java index e02a8cd5392..58ae3b8c1c5 100644 --- a/jdk/src/share/classes/java/time/chrono/ChronoLocalDate.java +++ b/jdk/src/share/classes/java/time/chrono/ChronoLocalDate.java @@ -69,7 +69,6 @@ import static java.time.temporal.ChronoUnit.DAYS; import java.time.DateTimeException; import java.time.LocalDate; import java.time.LocalTime; -import java.time.Period; import java.time.format.DateTimeFormatter; import java.time.temporal.ChronoField; import java.time.temporal.ChronoUnit; @@ -602,9 +601,12 @@ public interface ChronoLocalDate long until(Temporal endDate, TemporalUnit unit); /** - * Calculates the period between this date and another date as a {@code Period}. + * Calculates the period between this date and another date as a {@code ChronoPeriod}. + *
+ * This calculates the period between two dates. All supplied chronologies + * calculate the period using years, months and days, however the + * {@code ChronoPeriod} API allows the period to be represented using other units. *
- * This calculates the period between two dates in terms of years, months and days. * The start and end points are {@code this} and the specified date. * The result will be negative if the end is before the start. * The negative sign will be the same in each of year, month and day. @@ -614,12 +616,12 @@ public interface ChronoLocalDate *
* This instance is immutable and unaffected by this method call. * - * @param endDate the end date, exclusive, which may be in any chronology, not null + * @param endDateExclusive the end date, exclusive, which may be in any chronology, not null * @return the period between this date and the end date, not null * @throws DateTimeException if the period cannot be calculated * @throws ArithmeticException if numeric overflow occurs */ - Period until(ChronoLocalDate endDate); + ChronoPeriod until(ChronoLocalDate endDateExclusive); /** * Formats this date using the specified formatter. diff --git a/jdk/src/share/classes/java/time/chrono/ChronoPeriod.java b/jdk/src/share/classes/java/time/chrono/ChronoPeriod.java new file mode 100644 index 00000000000..0ac1d395143 --- /dev/null +++ b/jdk/src/share/classes/java/time/chrono/ChronoPeriod.java @@ -0,0 +1,365 @@ +/* + * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * This file is available under and governed by the GNU General Public + * License version 2 only, as published by the Free Software Foundation. + * However, the following notice accompanied the original version of this + * file: + * + * Copyright (c) 2013, Stephen Colebourne & Michael Nascimento Santos + * + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * * Neither the name of JSR-310 nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package java.time.chrono; + +import java.time.DateTimeException; +import java.time.temporal.ChronoUnit; +import java.time.temporal.Temporal; +import java.time.temporal.TemporalAmount; +import java.time.temporal.TemporalUnit; +import java.time.temporal.UnsupportedTemporalTypeException; +import java.util.List; +import java.util.Objects; + +/** + * A date-based amount of time, such as '3 years, 4 months and 5 days' in an + * arbitrary chronology, intended for advanced globalization use cases. + *
+ * This interface models a date-based amount of time in a calendar system. + * While most calendar systems use years, months and days, some do not. + * Therefore, this interface operates solely in terms of a set of supported + * units that are defined by the {@code Chronology}. + * The set of supported units is fixed for a given chronology. + * The amount of a supported unit may be set to zero. + *
+ * The period is modeled as a directed amount of time, meaning that individual + * parts of the period may be negative. + * + * @implSpec + * This interface must be implemented with care to ensure other classes operate correctly. + * All implementations that can be instantiated must be final, immutable and thread-safe. + * Subclasses should be Serializable wherever possible. + * + * @since 1.8 + */ +public interface ChronoPeriod + extends TemporalAmount { + + /** + * Obtains a {@code ChronoPeriod} consisting of amount of time between two dates. + *
+ * The start date is included, but the end date is not. + * The period is calculated using {@link ChronoLocalDate#until(ChronoLocalDate)}. + * As such, the calculation is chronology specific. + *
+ * The chronology of the first date is used. + * The chronology of the second date is ignored, with the date being converted + * to the target chronology system before the calculation starts. + *
+ * The result of this method can be a negative period if the end is before the start. + * In most cases, the positive/negative sign will be the same in each of the supported fields. + * + * @param startDateInclusive the start date, inclusive, specifying the chronology of the calculation, not null + * @param endDateExclusive the end date, exclusive, in any chronology, not null + * @return the period between this date and the end date, not null + * @see ChronoLocalDate#until(ChronoLocalDate) + */ + public static ChronoPeriod between(ChronoLocalDate startDateInclusive, ChronoLocalDate endDateExclusive) { + Objects.requireNonNull(startDateInclusive, "startDateInclusive"); + Objects.requireNonNull(endDateExclusive, "endDateExclusive"); + return startDateInclusive.until(endDateExclusive); + } + + //----------------------------------------------------------------------- + /** + * Gets the value of the requested unit. + *
+ * The supported units are chronology specific. + * They will typically be {@link ChronoUnit#YEARS YEARS}, + * {@link ChronoUnit#MONTHS MONTHS} and {@link ChronoUnit#DAYS DAYS}. + * Requesting an unsupported unit will throw an exception. + * + * @param unit the {@code TemporalUnit} for which to return the value + * @return the long value of the unit + * @throws DateTimeException if the unit is not supported + * @throws UnsupportedTemporalTypeException if the unit is not supported + */ + @Override + long get(TemporalUnit unit); + + /** + * Gets the set of units supported by this period. + *
+ * The supported units are chronology specific. + * They will typically be {@link ChronoUnit#YEARS YEARS}, + * {@link ChronoUnit#MONTHS MONTHS} and {@link ChronoUnit#DAYS DAYS}. + * They are returned in order from largest to smallest. + *
+ * This set can be used in conjunction with {@link #get(TemporalUnit)}
+ * to access the entire state of the period.
+ *
+ * @return a list containing the supported units, not null
+ */
+ @Override
+ List
+ * The period is defined by the chronology.
+ * It controls the supported units and restricts addition/subtraction
+ * to {@code ChronoLocalDate} instances of the same chronology.
+ *
+ * @return the chronology defining the period, not null
+ */
+ Chronology getChronology();
+
+ //-----------------------------------------------------------------------
+ /**
+ * Checks if all the supported units of this period are zero.
+ *
+ * @return true if this period is zero-length
+ */
+ default boolean isZero() {
+ for (TemporalUnit unit : getUnits()) {
+ if (get(unit) != 0) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ /**
+ * Checks if any of the supported units of this period are negative.
+ *
+ * @return true if any unit of this period is negative
+ */
+ default boolean isNegative() {
+ for (TemporalUnit unit : getUnits()) {
+ if (get(unit) < 0) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ //-----------------------------------------------------------------------
+ /**
+ * Returns a copy of this period with the specified period added.
+ *
+ * If the specified amount is a {@code ChronoPeriod} then it must have
+ * the same chronology as this period. Implementations may choose to
+ * accept or reject other {@code TemporalAmount} implementations.
+ *
+ * This instance is immutable and unaffected by this method call.
+ *
+ * @param amountToAdd the period to add, not null
+ * @return a {@code ChronoPeriod} based on this period with the requested period added, not null
+ * @throws ArithmeticException if numeric overflow occurs
+ */
+ ChronoPeriod plus(TemporalAmount amountToAdd);
+
+ /**
+ * Returns a copy of this period with the specified period subtracted.
+ *
+ * If the specified amount is a {@code ChronoPeriod} then it must have
+ * the same chronology as this period. Implementations may choose to
+ * accept or reject other {@code TemporalAmount} implementations.
+ *
+ * This instance is immutable and unaffected by this method call.
+ *
+ * @param amountToSubtract the period to subtract, not null
+ * @return a {@code ChronoPeriod} based on this period with the requested period subtracted, not null
+ * @throws ArithmeticException if numeric overflow occurs
+ */
+ ChronoPeriod minus(TemporalAmount amountToSubtract);
+
+ //-----------------------------------------------------------------------
+ /**
+ * Returns a new instance with each amount in this period in this period
+ * multiplied by the specified scalar.
+ *
+ * This returns a period with each supported unit individually multiplied.
+ * For example, a period of "2 years, -3 months and 4 days" multiplied by
+ * 3 will return "6 years, -9 months and 12 days".
+ * No normalization is performed.
+ *
+ * @param scalar the scalar to multiply by, not null
+ * @return a {@code ChronoPeriod} based on this period with the amounts multiplied
+ * by the scalar, not null
+ * @throws ArithmeticException if numeric overflow occurs
+ */
+ ChronoPeriod multipliedBy(int scalar);
+
+ /**
+ * Returns a new instance with each amount in this period negated.
+ *
+ * This returns a period with each supported unit individually negated.
+ * For example, a period of "2 years, -3 months and 4 days" will be
+ * negated to "-2 years, 3 months and -4 days".
+ * No normalization is performed.
+ *
+ * @return a {@code ChronoPeriod} based on this period with the amounts negated, not null
+ * @throws ArithmeticException if numeric overflow occurs, which only happens if
+ * one of the units has the value {@code Long.MIN_VALUE}
+ */
+ default ChronoPeriod negated() {
+ return multipliedBy(-1);
+ }
+
+ //-----------------------------------------------------------------------
+ /**
+ * Returns a copy of this period with the amounts of each unit normalized.
+ *
+ * The process of normalization is specific to each calendar system.
+ * For example, in the ISO calendar system, the years and months are
+ * normalized but the days are not, such that "15 months" would be
+ * normalized to "1 year and 3 months".
+ *
+ * This instance is immutable and unaffected by this method call.
+ *
+ * @return a {@code ChronoPeriod} based on this period with the amounts of each
+ * unit normalized, not null
+ * @throws ArithmeticException if numeric overflow occurs
+ */
+ ChronoPeriod normalized();
+
+ //-------------------------------------------------------------------------
+ /**
+ * Adds this period to the specified temporal object.
+ *
+ * This returns a temporal object of the same observable type as the input
+ * with this period added.
+ *
+ * In most cases, it is clearer to reverse the calling pattern by using
+ * {@link Temporal#plus(TemporalAmount)}.
+ *
+ * The specified temporal must have the same chronology as this period.
+ * This returns a temporal with the non-zero supported units added.
+ *
+ * This instance is immutable and unaffected by this method call.
+ *
+ * @param temporal the temporal object to adjust, not null
+ * @return an object of the same type with the adjustment made, not null
+ * @throws DateTimeException if unable to add
+ * @throws ArithmeticException if numeric overflow occurs
+ */
+ @Override
+ Temporal addTo(Temporal temporal);
+
+ /**
+ * Subtracts this period from the specified temporal object.
+ *
+ * This returns a temporal object of the same observable type as the input
+ * with this period subtracted.
+ *
+ * In most cases, it is clearer to reverse the calling pattern by using
+ * {@link Temporal#minus(TemporalAmount)}.
+ *
+ * The specified temporal must have the same chronology as this period.
+ * This returns a temporal with the non-zero supported units subtracted.
+ *
+ * This instance is immutable and unaffected by this method call.
+ *
+ * @param temporal the temporal object to adjust, not null
+ * @return an object of the same type with the adjustment made, not null
+ * @throws DateTimeException if unable to subtract
+ * @throws ArithmeticException if numeric overflow occurs
+ */
+ @Override
+ Temporal subtractFrom(Temporal temporal);
+
+ //-----------------------------------------------------------------------
+ /**
+ * Checks if this period is equal to another period, including the chronology.
+ *
+ * Compares this period with another ensuring that the type, each amount and
+ * the chronology are the same.
+ * Note that this means that a period of "15 Months" is not equal to a period
+ * of "1 Year and 3 Months".
+ *
+ * @param obj the object to check, null returns false
+ * @return true if this is equal to the other period
+ */
+ @Override
+ boolean equals(Object obj);
+
+ /**
+ * A hash code for this period.
+ *
+ * @return a suitable hash code
+ */
+ @Override
+ int hashCode();
+
+ //-----------------------------------------------------------------------
+ /**
+ * Outputs this period as a {@code String}.
+ *
+ * The output will include the period amounts and chronology.
+ *
+ * @return a string representation of this period, not null
+ */
+ @Override
+ String toString();
+
+}
diff --git a/jdk/src/share/classes/java/time/chrono/ChronoPeriodImpl.java b/jdk/src/share/classes/java/time/chrono/ChronoPeriodImpl.java
new file mode 100644
index 00000000000..d301adb2d03
--- /dev/null
+++ b/jdk/src/share/classes/java/time/chrono/ChronoPeriodImpl.java
@@ -0,0 +1,399 @@
+/*
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * Copyright (c) 2013, Stephen Colebourne & Michael Nascimento Santos
+ *
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * * Redistributions of source code must retain the above copyright notice,
+ * this list of conditions and the following disclaimer.
+ *
+ * * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following disclaimer in the documentation
+ * and/or other materials provided with the distribution.
+ *
+ * * Neither the name of JSR-310 nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
+ * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+ * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+package java.time.chrono;
+
+import static java.time.temporal.ChronoField.MONTH_OF_YEAR;
+import static java.time.temporal.ChronoUnit.DAYS;
+import static java.time.temporal.ChronoUnit.MONTHS;
+import static java.time.temporal.ChronoUnit.YEARS;
+
+import java.io.DataInput;
+import java.io.DataOutput;
+import java.io.IOException;
+import java.io.InvalidObjectException;
+import java.io.ObjectStreamException;
+import java.io.Serializable;
+import java.time.DateTimeException;
+import java.time.temporal.ChronoUnit;
+import java.time.temporal.Temporal;
+import java.time.temporal.TemporalAccessor;
+import java.time.temporal.TemporalAmount;
+import java.time.temporal.TemporalQuery;
+import java.time.temporal.TemporalUnit;
+import java.time.temporal.UnsupportedTemporalTypeException;
+import java.time.temporal.ValueRange;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+import java.util.Objects;
+
+/**
+ * A period expressed in terms of a standard year-month-day calendar system.
+ *
+ * This class is used by applications seeking to handle dates in non-ISO calendar systems.
+ * For example, the Japanese, Minguo, Thai Buddhist and others.
+ *
+ * @implSpec
+ * This class is immutable nad thread-safe.
+ *
+ * @since 1.8
+ */
+final class ChronoPeriodImpl
+ implements ChronoPeriod, Serializable {
+ // this class is only used by JDK chronology implementations and makes assumptions based on that fact
+
+ /**
+ * Serialization version.
+ */
+ private static final long serialVersionUID = 57387258289L;
+
+ /**
+ * The set of supported units.
+ */
+ private final static List
+ * This returns a period tied to this chronology using the specified
+ * years, months and days. All supplied chronologies use periods
+ * based on years, months and days, however the {@code ChronoPeriod} API
+ * allows the period to be represented using other units.
+ *
+ * @implSpec
+ * The default implementation returns an implementation class suitable
+ * for most calendar systems. It is based solely on the three units.
+ * Normalization, addition and subtraction derive the number of months
+ * in a year from the {@link #range(ChronoField)}. If the number of
+ * months within a year is fixed, then the calculation approach for
+ * addition, subtraction and normalization is slightly different.
+ *
+ * If implementing an unusual calendar system that is not based on
+ * years, months and days, or where you want direct control, then
+ * the {@code ChronoPeriod} interface must be directly implemented.
+ *
+ * The returned period is immutable and thread-safe.
+ *
+ * @param years the number of years, may be negative
+ * @param months the number of years, may be negative
+ * @param days the number of years, may be negative
+ * @return the period in terms of this chronology, not null
+ */
+ public ChronoPeriod period(int years, int months, int days) {
+ return new ChronoPeriodImpl(this, years, months, days);
+ }
+
//-----------------------------------------------------------------------
/**
* Compares this chronology to another chronology.
diff --git a/jdk/src/share/classes/java/time/chrono/HijrahDate.java b/jdk/src/share/classes/java/time/chrono/HijrahDate.java
index c0d942396cd..d2c9929316c 100644
--- a/jdk/src/share/classes/java/time/chrono/HijrahDate.java
+++ b/jdk/src/share/classes/java/time/chrono/HijrahDate.java
@@ -73,7 +73,6 @@ import java.time.Clock;
import java.time.DateTimeException;
import java.time.LocalDate;
import java.time.LocalTime;
-import java.time.Period;
import java.time.ZoneId;
import java.time.temporal.ChronoField;
import java.time.temporal.TemporalAccessor;
@@ -582,7 +581,7 @@ public final class HijrahDate
}
@Override
- public Period until(ChronoLocalDate endDate) {
+ public ChronoPeriod until(ChronoLocalDate endDate) {
// TODO: untested
HijrahDate end = getChronology().date(endDate);
long totalMonths = (end.prolepticYear - this.prolepticYear) * 12 + (end.monthOfYear - this.monthOfYear); // safe
@@ -597,7 +596,7 @@ public final class HijrahDate
}
long years = totalMonths / 12; // safe
int months = (int) (totalMonths % 12); // safe
- return Period.of(Math.toIntExact(years), months, days);
+ return getChronology().period(Math.toIntExact(years), months, days);
}
//-----------------------------------------------------------------------
diff --git a/jdk/src/share/classes/java/time/chrono/IsoChronology.java b/jdk/src/share/classes/java/time/chrono/IsoChronology.java
index 2012e64e04d..9638f6eea4f 100644
--- a/jdk/src/share/classes/java/time/chrono/IsoChronology.java
+++ b/jdk/src/share/classes/java/time/chrono/IsoChronology.java
@@ -77,6 +77,7 @@ import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.Month;
+import java.time.Period;
import java.time.Year;
import java.time.ZoneId;
import java.time.ZonedDateTime;
@@ -565,6 +566,24 @@ public final class IsoChronology extends Chronology implements Serializable {
return field.range();
}
+ //-----------------------------------------------------------------------
+ /**
+ * Obtains a period for this chronology based on years, months and days.
+ *
+ * This returns a period tied to the ISO chronology using the specified
+ * years, months and days. See {@link Period} for further details.
+ *
+ * @param years the number of years, may be negative
+ * @param months the number of years, may be negative
+ * @param days the number of years, may be negative
+ * @return the period in terms of this chronology, not null
+ * @return the ISO period, not null
+ */
+ @Override // override with covariant return type
+ public Period period(int years, int months, int days) {
+ return Period.of(years, months, days);
+ }
+
//-----------------------------------------------------------------------
/**
* Writes the Chronology using a
diff --git a/jdk/src/share/classes/java/time/chrono/JapaneseDate.java b/jdk/src/share/classes/java/time/chrono/JapaneseDate.java
index bc9f473486d..ae4708dbaff 100644
--- a/jdk/src/share/classes/java/time/chrono/JapaneseDate.java
+++ b/jdk/src/share/classes/java/time/chrono/JapaneseDate.java
@@ -659,8 +659,9 @@ public final class JapaneseDate
}
@Override
- public Period until(ChronoLocalDate endDate) {
- return isoDate.until(endDate);
+ public ChronoPeriod until(ChronoLocalDate endDate) {
+ Period period = isoDate.until(endDate);
+ return getChronology().period(period.getYears(), period.getMonths(), period.getDays());
}
@Override // override for performance
diff --git a/jdk/src/share/classes/java/time/chrono/MinguoDate.java b/jdk/src/share/classes/java/time/chrono/MinguoDate.java
index fd10e0e985e..42e0dab0da5 100644
--- a/jdk/src/share/classes/java/time/chrono/MinguoDate.java
+++ b/jdk/src/share/classes/java/time/chrono/MinguoDate.java
@@ -421,8 +421,9 @@ public final class MinguoDate
}
@Override
- public Period until(ChronoLocalDate endDate) {
- return isoDate.until(endDate);
+ public ChronoPeriod until(ChronoLocalDate endDate) {
+ Period period = isoDate.until(endDate);
+ return getChronology().period(period.getYears(), period.getMonths(), period.getDays());
}
@Override // override for performance
diff --git a/jdk/src/share/classes/java/time/chrono/Ser.java b/jdk/src/share/classes/java/time/chrono/Ser.java
index cc99f481f8c..5a4e3c12623 100644
--- a/jdk/src/share/classes/java/time/chrono/Ser.java
+++ b/jdk/src/share/classes/java/time/chrono/Ser.java
@@ -104,6 +104,7 @@ final class Ser implements Externalizable {
static final byte HIJRAH_DATE_TYPE = 6;
static final byte MINGUO_DATE_TYPE = 7;
static final byte THAIBUDDHIST_DATE_TYPE = 8;
+ static final byte CHRONO_PERIOD_TYPE = 9;
/** The type being serialized. */
private byte type;
@@ -183,6 +184,9 @@ final class Ser implements Externalizable {
case THAIBUDDHIST_DATE_TYPE:
((ThaiBuddhistDate) object).writeExternal(out);
break;
+ case CHRONO_PERIOD_TYPE:
+ ((ChronoPeriodImpl) object).writeExternal(out);
+ break;
default:
throw new InvalidClassException("Unknown serialized type");
}
@@ -235,6 +239,7 @@ final class Ser implements Externalizable {
case HIJRAH_DATE_TYPE: return HijrahDate.readExternal(in);
case MINGUO_DATE_TYPE: return MinguoDate.readExternal(in);
case THAIBUDDHIST_DATE_TYPE: return ThaiBuddhistDate.readExternal(in);
+ case CHRONO_PERIOD_TYPE: return ChronoPeriodImpl.readExternal(in);
default: throw new StreamCorruptedException("Unknown serialized type");
}
}
diff --git a/jdk/src/share/classes/java/time/chrono/ThaiBuddhistDate.java b/jdk/src/share/classes/java/time/chrono/ThaiBuddhistDate.java
index 648793b7337..89895c8ac48 100644
--- a/jdk/src/share/classes/java/time/chrono/ThaiBuddhistDate.java
+++ b/jdk/src/share/classes/java/time/chrono/ThaiBuddhistDate.java
@@ -421,8 +421,9 @@ public final class ThaiBuddhistDate
}
@Override
- public Period until(ChronoLocalDate endDate) {
- return isoDate.until(endDate);
+ public ChronoPeriod until(ChronoLocalDate endDate) {
+ Period period = isoDate.until(endDate);
+ return getChronology().period(period.getYears(), period.getMonths(), period.getDays());
}
@Override // override for performance
diff --git a/jdk/src/share/classes/java/time/temporal/Temporal.java b/jdk/src/share/classes/java/time/temporal/Temporal.java
index af8424c1560..54110bed771 100644
--- a/jdk/src/share/classes/java/time/temporal/Temporal.java
+++ b/jdk/src/share/classes/java/time/temporal/Temporal.java
@@ -170,7 +170,8 @@ public interface Temporal extends TemporalAccessor {
*
*
* @implSpec
- * Implementations must not alter either this object.
+ *
+ * Implementations must not alter either this object or the specified temporal object.
* Instead, an adjusted copy of the original must be returned.
* This provides equivalent, safe behavior for immutable and mutable implementations.
*
@@ -209,7 +210,7 @@ public interface Temporal extends TemporalAccessor {
* is obtained by invoking {@code TemporalField.adjustInto(Temporal, long)}
* passing {@code this} as the first argument.
*
- * Implementations must not alter either this object or the specified temporal object.
+ * Implementations must not alter this object.
* Instead, an adjusted copy of the original must be returned.
* This provides equivalent, safe behavior for immutable and mutable implementations.
*
@@ -232,16 +233,17 @@ public interface Temporal extends TemporalAccessor {
*
* Some example code indicating how and why this method is used:
*
* Note that calling {@code plus} followed by {@code minus} is not guaranteed to
* return the same date-time.
*
* @implSpec
- * Implementations must not alter either this object.
+ *
+ * Implementations must not alter either this object or the specified temporal object.
* Instead, an adjusted copy of the original must be returned.
* This provides equivalent, safe behavior for immutable and mutable implementations.
*
@@ -280,7 +282,7 @@ public interface Temporal extends TemporalAccessor {
* is obtained by invoking {@code TemporalUnit.addTo(Temporal, long)}
* passing {@code this} as the first argument.
*
- * Implementations must not alter either this object or the specified temporal object.
+ * Implementations must not alter this object.
* Instead, an adjusted copy of the original must be returned.
* This provides equivalent, safe behavior for immutable and mutable implementations.
*
@@ -303,16 +305,17 @@ public interface Temporal extends TemporalAccessor {
*
* Some example code indicating how and why this method is used:
*
* Note that calling {@code plus} followed by {@code minus} is not guaranteed to
* return the same date-time.
*
* @implSpec
- * Implementations must not alter either this object.
+ *
+ * Implementations must not alter either this object or the specified temporal object.
* Instead, an adjusted copy of the original must be returned.
* This provides equivalent, safe behavior for immutable and mutable implementations.
*
@@ -345,7 +348,7 @@ public interface Temporal extends TemporalAccessor {
* @implSpec
* Implementations must behave in a manor equivalent to the default method behavior.
*
- * Implementations must not alter either this object or the specified temporal object.
+ * Implementations must not alter this object.
* Instead, an adjusted copy of the original must be returned.
* This provides equivalent, safe behavior for immutable and mutable implementations.
*
diff --git a/jdk/test/java/time/tck/java/time/TCKPeriod.java b/jdk/test/java/time/tck/java/time/TCKPeriod.java
index 3a1fe42ec45..7743512002f 100644
--- a/jdk/test/java/time/tck/java/time/TCKPeriod.java
+++ b/jdk/test/java/time/tck/java/time/TCKPeriod.java
@@ -60,6 +60,7 @@
package tck.java.time;
import static java.time.temporal.ChronoUnit.DAYS;
+import static java.time.temporal.ChronoUnit.HOURS;
import static java.time.temporal.ChronoUnit.YEARS;
import static org.testng.Assert.assertEquals;
@@ -67,6 +68,7 @@ import java.time.DateTimeException;
import java.time.Duration;
import java.time.LocalDate;
import java.time.Period;
+import java.time.chrono.ThaiBuddhistChronology;
import java.time.format.DateTimeParseException;
import java.time.temporal.ChronoUnit;
import java.time.temporal.Temporal;
@@ -212,6 +214,41 @@ public class TCKPeriod extends AbstractTCKTest {
Period.from(amount);
}
+ @Test(expectedExceptions = DateTimeException.class)
+ public void factory_from_TemporalAmount_DaysHours() {
+ TemporalAmount amount = new TemporalAmount() {
+ @Override
+ public long get(TemporalUnit unit) {
+ if (unit == DAYS) {
+ return 1;
+ } else {
+ return 2;
+ }
+ }
+ @Override
+ public List
+ * // these two lines are equivalent, but the second approach is recommended
+ * dateTime = thisPeriod.addTo(dateTime);
+ * dateTime = dateTime.plus(thisPeriod);
+ *
+ *
+ * // these two lines are equivalent, but the second approach is recommended
+ * dateTime = thisPeriod.subtractFrom(dateTime);
+ * dateTime = dateTime.minus(thisPeriod);
+ *
+ *
+ * out.writeByte(12); // identifies this as a ChronoPeriodImpl
+ * out.writeUTF(getId()); // the chronology
+ * out.writeInt(years);
+ * out.writeInt(months);
+ * out.writeInt(days);
+ *
+ *
+ * @return the instance of {@code Ser}, not null
+ */
+ protected Object writeReplace() {
+ return new Ser(Ser.CHRONO_PERIOD_TYPE, this);
+ }
+
+ /**
+ * Defend against malicious streams.
+ * @return never
+ * @throws InvalidObjectException always
+ */
+ private Object readResolve() throws ObjectStreamException {
+ throw new InvalidObjectException("Deserialization via serialization delegate");
+ }
+
+ void writeExternal(DataOutput out) throws IOException {
+ out.writeUTF(chrono.getId());
+ out.writeInt(years);
+ out.writeInt(months);
+ out.writeInt(days);
+ }
+
+ static ChronoPeriodImpl readExternal(DataInput in) throws IOException {
+ Chronology chrono = Chronology.of(in.readUTF());
+ int years = in.readInt();
+ int months = in.readInt();
+ int days = in.readInt();
+ return new ChronoPeriodImpl(chrono, years, months, days);
+ }
+
+}
diff --git a/jdk/src/share/classes/java/time/chrono/Chronology.java b/jdk/src/share/classes/java/time/chrono/Chronology.java
index 36c9d31c3fd..ed40f4138f0 100644
--- a/jdk/src/share/classes/java/time/chrono/Chronology.java
+++ b/jdk/src/share/classes/java/time/chrono/Chronology.java
@@ -91,14 +91,11 @@ import java.time.DayOfWeek;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalTime;
-import java.time.Month;
-import java.time.Year;
import java.time.ZoneId;
import java.time.format.DateTimeFormatterBuilder;
import java.time.format.ResolverStyle;
import java.time.format.TextStyle;
import java.time.temporal.ChronoField;
-import java.time.temporal.Temporal;
import java.time.temporal.TemporalAccessor;
import java.time.temporal.TemporalAdjuster;
import java.time.temporal.TemporalField;
@@ -1190,6 +1187,38 @@ public abstract class Chronology implements Comparable
- * date = date.plus(period); // add a Period instance
- * date = date.plus(duration); // add a Duration instance
- * date = date.plus(workingDays(6)); // example user-written workingDays method
+ * date = date.plus(period); // add a Period instance
+ * date = date.plus(duration); // add a Duration instance
+ * date = date.plus(workingDays(6)); // example user-written workingDays method
*
*
- * date = date.minus(period); // subtract a Period instance
- * date = date.minus(duration); // subtract a Duration instance
- * date = date.minus(workingDays(6)); // example user-written workingDays method
+ * date = date.minus(period); // subtract a Period instance
+ * date = date.minus(duration); // subtract a Duration instance
+ * date = date.minus(workingDays(6)); // example user-written workingDays method
*
*