1 /*
   2  * Copyright (c) 2012, 2020, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 /*
  27  * This file is available under and governed by the GNU General Public
  28  * License version 2 only, as published by the Free Software Foundation.
  29  * However, the following notice accompanied the original version of this
  30  * file:
  31  *
  32  * Copyright (c) 2008-2012, Stephen Colebourne & Michael Nascimento Santos
  33  *
  34  * All rights reserved.
  35  *
  36  * Redistribution and use in source and binary forms, with or without
  37  * modification, are permitted provided that the following conditions are met:
  38  *
  39  *  * Redistributions of source code must retain the above copyright notice,
  40  *    this list of conditions and the following disclaimer.
  41  *
  42  *  * Redistributions in binary form must reproduce the above copyright notice,
  43  *    this list of conditions and the following disclaimer in the documentation
  44  *    and/or other materials provided with the distribution.
  45  *
  46  *  * Neither the name of JSR-310 nor the names of its contributors
  47  *    may be used to endorse or promote products derived from this software
  48  *    without specific prior written permission.
  49  *
  50  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  51  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  52  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  53  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  54  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
  55  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  56  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  57  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  58  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  59  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  60  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  61  */
  62 package java.time;
  63 
  64 import static java.time.temporal.ChronoUnit.DAYS;
  65 import static java.time.temporal.ChronoUnit.MONTHS;
  66 import static java.time.temporal.ChronoUnit.YEARS;
  67 
  68 import java.io.DataInput;
  69 import java.io.DataOutput;
  70 import java.io.IOException;
  71 import java.io.InvalidObjectException;
  72 import java.io.ObjectInputStream;
  73 import java.io.Serializable;
  74 import java.time.chrono.ChronoLocalDate;
  75 import java.time.chrono.ChronoPeriod;
  76 import java.time.chrono.Chronology;
  77 import java.time.chrono.IsoChronology;
  78 import java.time.format.DateTimeParseException;
  79 import java.time.temporal.ChronoUnit;
  80 import java.time.temporal.Temporal;
  81 import java.time.temporal.TemporalAccessor;
  82 import java.time.temporal.TemporalAmount;
  83 import java.time.temporal.TemporalQueries;
  84 import java.time.temporal.TemporalUnit;
  85 import java.time.temporal.UnsupportedTemporalTypeException;
  86 import java.util.List;
  87 import java.util.Objects;
  88 import java.util.regex.Matcher;
  89 import java.util.regex.Pattern;
  90 
  91 /**
  92  * A date-based amount of time in the ISO-8601 calendar system,
  93  * such as '2 years, 3 months and 4 days'.
  94  * <p>
  95  * This class models a quantity or amount of time in terms of years, months and days.
  96  * See {@link Duration} for the time-based equivalent to this class.
  97  * <p>
  98  * Durations and periods differ in their treatment of daylight savings time
  99  * when added to {@link ZonedDateTime}. A {@code Duration} will add an exact
 100  * number of seconds, thus a duration of one day is always exactly 24 hours.
 101  * By contrast, a {@code Period} will add a conceptual day, trying to maintain
 102  * the local time.
 103  * <p>
 104  * For example, consider adding a period of one day and a duration of one day to
 105  * 18:00 on the evening before a daylight savings gap. The {@code Period} will add
 106  * the conceptual day and result in a {@code ZonedDateTime} at 18:00 the following day.
 107  * By contrast, the {@code Duration} will add exactly 24 hours, resulting in a
 108  * {@code ZonedDateTime} at 19:00 the following day (assuming a one hour DST gap).
 109  * <p>
 110  * The supported units of a period are {@link ChronoUnit#YEARS YEARS},
 111  * {@link ChronoUnit#MONTHS MONTHS} and {@link ChronoUnit#DAYS DAYS}.
 112  * All three fields are always present, but may be set to zero.
 113  * <p>
 114  * The ISO-8601 calendar system is the modern civil calendar system used today
 115  * in most of the world. It is equivalent to the proleptic Gregorian calendar
 116  * system, in which today's rules for leap years are applied for all time.
 117  * <p>
 118  * The period is modeled as a directed amount of time, meaning that individual parts of the
 119  * period may be negative.
 120  * <p>
 121  * This is a <a href="{@docRoot}/java.base/java/lang/doc-files/ValueBased.html">value-based</a>
 122  * class; programmers should treat instances that are {@linkplain #equals(Object) equal}
 123  * as interchangeable and should not use instances for synchronization, mutexes, or
 124  * with {@linkplain java.lang.ref.Reference object references}.
 125  *
 126  * <div class="preview-block">
 127  *      <div class="preview-comment">
 128  *          When preview features are enabled, {@code Period} is a {@linkplain Class#isValue value class}.
 129  *          Use of value class instances for synchronization, mutexes, or with
 130  *          {@linkplain java.lang.ref.Reference object references} result in
 131  *          {@link IdentityException}.
 132  *      </div>
 133  * </div>
 134  *
 135  * @implSpec
 136  * This class is immutable and thread-safe.
 137  *
 138  * @since 1.8
 139  */
 140 @jdk.internal.ValueBased
 141 @jdk.internal.MigratedValueClass
 142 public final class Period
 143         implements ChronoPeriod, Serializable {
 144 
 145     /**
 146      * A constant for a period of zero.
 147      */
 148     public static final Period ZERO = new Period(0, 0, 0);
 149     /**
 150      * Serialization version.
 151      */
 152     @java.io.Serial
 153     private static final long serialVersionUID = -3587258372562876L;
 154     /**
 155      * The pattern for parsing.
 156      */
 157     private static final Pattern PATTERN =
 158             Pattern.compile("([-+]?)P(?:([-+]?[0-9]+)Y)?(?:([-+]?[0-9]+)M)?(?:([-+]?[0-9]+)W)?(?:([-+]?[0-9]+)D)?", Pattern.CASE_INSENSITIVE);
 159 
 160     /**
 161      * The set of supported units.
 162      */
 163     private static final List<TemporalUnit> SUPPORTED_UNITS = List.of(YEARS, MONTHS, DAYS);
 164 
 165     /**
 166      * The number of years.
 167      */
 168     private final int years;
 169     /**
 170      * The number of months.
 171      */
 172     private final int months;
 173     /**
 174      * The number of days.
 175      */
 176     private final int days;
 177 
 178     //-----------------------------------------------------------------------
 179     /**
 180      * Obtains a {@code Period} representing a number of years.
 181      * <p>
 182      * The resulting period will have the specified years.
 183      * The months and days units will be zero.
 184      *
 185      * @param years  the number of years, positive or negative
 186      * @return the period of years, not null
 187      */
 188     public static Period ofYears(int years) {
 189         return create(years, 0, 0);
 190     }
 191 
 192     /**
 193      * Obtains a {@code Period} representing a number of months.
 194      * <p>
 195      * The resulting period will have the specified months.
 196      * The years and days units will be zero.
 197      *
 198      * @param months  the number of months, positive or negative
 199      * @return the period of months, not null
 200      */
 201     public static Period ofMonths(int months) {
 202         return create(0, months, 0);
 203     }
 204 
 205     /**
 206      * Obtains a {@code Period} representing a number of weeks.
 207      * <p>
 208      * The resulting period will be day-based, with the amount of days
 209      * equal to the number of weeks multiplied by 7.
 210      * The years and months units will be zero.
 211      *
 212      * @param weeks  the number of weeks, positive or negative
 213      * @return the period, with the input weeks converted to days, not null
 214      */
 215     public static Period ofWeeks(int weeks) {
 216         return create(0, 0, Math.multiplyExact(weeks, 7));
 217     }
 218 
 219     /**
 220      * Obtains a {@code Period} representing a number of days.
 221      * <p>
 222      * The resulting period will have the specified days.
 223      * The years and months units will be zero.
 224      *
 225      * @param days  the number of days, positive or negative
 226      * @return the period of days, not null
 227      */
 228     public static Period ofDays(int days) {
 229         return create(0, 0, days);
 230     }
 231 
 232     //-----------------------------------------------------------------------
 233     /**
 234      * Obtains a {@code Period} representing a number of years, months and days.
 235      * <p>
 236      * This creates an instance based on years, months and days.
 237      *
 238      * @param years  the amount of years, may be negative
 239      * @param months  the amount of months, may be negative
 240      * @param days  the amount of days, may be negative
 241      * @return the period of years, months and days, not null
 242      */
 243     public static Period of(int years, int months, int days) {
 244         return create(years, months, days);
 245     }
 246 
 247     //-----------------------------------------------------------------------
 248     /**
 249      * Obtains an instance of {@code Period} from a temporal amount.
 250      * <p>
 251      * This obtains a period based on the specified amount.
 252      * A {@code TemporalAmount} represents an  amount of time, which may be
 253      * date-based or time-based, which this factory extracts to a {@code Period}.
 254      * <p>
 255      * The conversion loops around the set of units from the amount and uses
 256      * the {@link ChronoUnit#YEARS YEARS}, {@link ChronoUnit#MONTHS MONTHS}
 257      * and {@link ChronoUnit#DAYS DAYS} units to create a period.
 258      * If any other units are found then an exception is thrown.
 259      * <p>
 260      * If the amount is a {@code ChronoPeriod} then it must use the ISO chronology.
 261      *
 262      * @param amount  the temporal amount to convert, not null
 263      * @return the equivalent period, not null
 264      * @throws DateTimeException if unable to convert to a {@code Period}
 265      * @throws ArithmeticException if the amount of years, months or days exceeds an int
 266      */
 267     public static Period from(TemporalAmount amount) {
 268         if (amount instanceof Period) {
 269             return (Period) amount;
 270         }
 271         if (amount instanceof ChronoPeriod) {
 272             if (IsoChronology.INSTANCE.equals(((ChronoPeriod) amount).getChronology()) == false) {
 273                 throw new DateTimeException("Period requires ISO chronology: " + amount);
 274             }
 275         }
 276         Objects.requireNonNull(amount, "amount");
 277         int years = 0;
 278         int months = 0;
 279         int days = 0;
 280         for (TemporalUnit unit : amount.getUnits()) {
 281             long unitAmount = amount.get(unit);
 282             if (unit == ChronoUnit.YEARS) {
 283                 years = Math.toIntExact(unitAmount);
 284             } else if (unit == ChronoUnit.MONTHS) {
 285                 months = Math.toIntExact(unitAmount);
 286             } else if (unit == ChronoUnit.DAYS) {
 287                 days = Math.toIntExact(unitAmount);
 288             } else {
 289                 throw new DateTimeException("Unit must be Years, Months or Days, but was " + unit);
 290             }
 291         }
 292         return create(years, months, days);
 293     }
 294 
 295     //-----------------------------------------------------------------------
 296     /**
 297      * Obtains a {@code Period} from a text string such as {@code PnYnMnD}.
 298      * <p>
 299      * This will parse the string produced by {@code toString()} which is
 300      * based on the ISO-8601 period formats {@code PnYnMnD} and {@code PnW}.
 301      * <p>
 302      * The string starts with an optional sign, denoted by the ASCII negative
 303      * or positive symbol. If negative, the whole period is negated.
 304      * The ASCII letter "P" is next in upper or lower case.
 305      * There are then four sections, each consisting of a number and a suffix.
 306      * At least one of the four sections must be present.
 307      * The sections have suffixes in ASCII of "Y", "M", "W" and "D" for
 308      * years, months, weeks and days, accepted in upper or lower case.
 309      * The suffixes must occur in order.
 310      * The number part of each section must consist of ASCII digits.
 311      * The number may be prefixed by the ASCII negative or positive symbol.
 312      * The number must parse to an {@code int}.
 313      * <p>
 314      * The leading plus/minus sign, and negative values for other units are
 315      * not part of the ISO-8601 standard. In addition, ISO-8601 does not
 316      * permit mixing between the {@code PnYnMnD} and {@code PnW} formats.
 317      * Any week-based input is multiplied by 7 and treated as a number of days.
 318      * <p>
 319      * For example, the following are valid inputs:
 320      * <pre>
 321      *   "P2Y"             -- Period.ofYears(2)
 322      *   "P3M"             -- Period.ofMonths(3)
 323      *   "P4W"             -- Period.ofWeeks(4)
 324      *   "P5D"             -- Period.ofDays(5)
 325      *   "P1Y2M3D"         -- Period.of(1, 2, 3)
 326      *   "P1Y2M3W4D"       -- Period.of(1, 2, 25)
 327      *   "P-1Y2M"          -- Period.of(-1, 2, 0)
 328      *   "-P1Y2M"          -- Period.of(-1, -2, 0)
 329      * </pre>
 330      *
 331      * @param text  the text to parse, not null
 332      * @return the parsed period, not null
 333      * @throws DateTimeParseException if the text cannot be parsed to a period
 334      */
 335     public static Period parse(CharSequence text) {
 336         Objects.requireNonNull(text, "text");
 337         Matcher matcher = PATTERN.matcher(text);
 338         if (matcher.matches()) {
 339             int negate = (charMatch(text, matcher.start(1), matcher.end(1), '-') ? -1 : 1);
 340             int yearStart = matcher.start(2), yearEnd = matcher.end(2);
 341             int monthStart = matcher.start(3), monthEnd = matcher.end(3);
 342             int weekStart = matcher.start(4), weekEnd = matcher.end(4);
 343             int dayStart = matcher.start(5), dayEnd = matcher.end(5);
 344             if (yearStart >= 0 || monthStart >= 0 || weekStart >= 0 || dayStart >= 0) {
 345                 try {
 346                     int years = parseNumber(text, yearStart, yearEnd, negate);
 347                     int months = parseNumber(text, monthStart, monthEnd, negate);
 348                     int weeks = parseNumber(text, weekStart, weekEnd, negate);
 349                     int days = parseNumber(text, dayStart, dayEnd, negate);
 350                     days = Math.addExact(days, Math.multiplyExact(weeks, 7));
 351                     return create(years, months, days);
 352                 } catch (NumberFormatException ex) {
 353                     throw new DateTimeParseException("Text cannot be parsed to a Period", text, 0, ex);
 354                 }
 355             }
 356         }
 357         throw new DateTimeParseException("Text cannot be parsed to a Period", text, 0);
 358     }
 359 
 360     private static boolean charMatch(CharSequence text, int start, int end, char c) {
 361         return (start >= 0 && end == start + 1 && text.charAt(start) == c);
 362     }
 363 
 364     private static int parseNumber(CharSequence text, int start, int end, int negate) {
 365         if (start < 0 || end < 0) {
 366             return 0;
 367         }
 368         int val = Integer.parseInt(text, start, end, 10);
 369         try {
 370             return Math.multiplyExact(val, negate);
 371         } catch (ArithmeticException ex) {
 372             throw new DateTimeParseException("Text cannot be parsed to a Period", text, 0, ex);
 373         }
 374     }
 375 
 376     //-----------------------------------------------------------------------
 377     /**
 378      * Obtains a {@code Period} consisting of the number of years, months,
 379      * and days between two dates.
 380      * <p>
 381      * The start date is included, but the end date is not.
 382      * The period is calculated by removing complete months, then calculating
 383      * the remaining number of days, adjusting to ensure that both have the same sign.
 384      * The number of months is then split into years and months based on a 12 month year.
 385      * A month is considered if the end day-of-month is greater than or equal to the start day-of-month.
 386      * For example, from {@code 2010-01-15} to {@code 2011-03-18} is one year, two months and three days.
 387      * <p>
 388      * The result of this method can be a negative period if the end is before the start.
 389      * The negative sign will be the same in each of year, month and day.
 390      *
 391      * @param startDateInclusive  the start date, inclusive, not null
 392      * @param endDateExclusive  the end date, exclusive, not null
 393      * @return the period between this date and the end date, not null
 394      * @see ChronoLocalDate#until(ChronoLocalDate)
 395      */
 396     public static Period between(LocalDate startDateInclusive, LocalDate endDateExclusive) {
 397         return startDateInclusive.until(endDateExclusive);
 398     }
 399 
 400     //-----------------------------------------------------------------------
 401     /**
 402      * Creates an instance.
 403      *
 404      * @param years  the amount
 405      * @param months  the amount
 406      * @param days  the amount
 407      */
 408     private static Period create(int years, int months, int days) {
 409         if ((years | months | days) == 0) {
 410             return ZERO;
 411         }
 412         return new Period(years, months, days);
 413     }
 414 
 415     /**
 416      * Constructor.
 417      *
 418      * @param years  the amount
 419      * @param months  the amount
 420      * @param days  the amount
 421      */
 422     private Period(int years, int months, int days) {
 423         this.years = years;
 424         this.months = months;
 425         this.days = days;
 426     }
 427 
 428     //-----------------------------------------------------------------------
 429     /**
 430      * Gets the value of the requested unit.
 431      * <p>
 432      * This returns a value for each of the three supported units,
 433      * {@link ChronoUnit#YEARS YEARS}, {@link ChronoUnit#MONTHS MONTHS} and
 434      * {@link ChronoUnit#DAYS DAYS}.
 435      * All other units throw an exception.
 436      *
 437      * @param unit the {@code TemporalUnit} for which to return the value
 438      * @return the long value of the unit
 439      * @throws DateTimeException if the unit is not supported
 440      * @throws UnsupportedTemporalTypeException if the unit is not supported
 441      */
 442     @Override
 443     public long get(TemporalUnit unit) {
 444         if (unit == ChronoUnit.YEARS) {
 445             return getYears();
 446         } else if (unit == ChronoUnit.MONTHS) {
 447             return getMonths();
 448         } else if (unit == ChronoUnit.DAYS) {
 449             return getDays();
 450         } else {
 451             throw new UnsupportedTemporalTypeException("Unsupported unit: " + unit);
 452         }
 453     }
 454 
 455     /**
 456      * Gets the set of units supported by this period.
 457      * <p>
 458      * The supported units are {@link ChronoUnit#YEARS YEARS},
 459      * {@link ChronoUnit#MONTHS MONTHS} and {@link ChronoUnit#DAYS DAYS}.
 460      * They are returned in the order years, months, days.
 461      * <p>
 462      * This set can be used in conjunction with {@link #get(TemporalUnit)}
 463      * to access the entire state of the period.
 464      *
 465      * @return a list containing the years, months and days units, not null
 466      */
 467     @Override
 468     public List<TemporalUnit> getUnits() {
 469         return SUPPORTED_UNITS;
 470     }
 471 
 472     /**
 473      * Gets the chronology of this period, which is the ISO calendar system.
 474      * <p>
 475      * The {@code Chronology} represents the calendar system in use.
 476      * The ISO-8601 calendar system is the modern civil calendar system used today
 477      * in most of the world. It is equivalent to the proleptic Gregorian calendar
 478      * system, in which today's rules for leap years are applied for all time.
 479      *
 480      * @return the ISO chronology, not null
 481      */
 482     @Override
 483     public IsoChronology getChronology() {
 484         return IsoChronology.INSTANCE;
 485     }
 486 
 487     //-----------------------------------------------------------------------
 488     /**
 489      * Checks if all three units of this period are zero.
 490      * <p>
 491      * A zero period has the value zero for the years, months and days units.
 492      *
 493      * @return true if this period is zero-length
 494      */
 495     public boolean isZero() {
 496         return (this == ZERO);
 497     }
 498 
 499     /**
 500      * Checks if any of the three units of this period are negative.
 501      * <p>
 502      * This checks whether the years, months or days units are less than zero.
 503      *
 504      * @return true if any unit of this period is negative
 505      */
 506     public boolean isNegative() {
 507         return years < 0 || months < 0 || days < 0;
 508     }
 509 
 510     //-----------------------------------------------------------------------
 511     /**
 512      * Gets the amount of years of this period.
 513      * <p>
 514      * This returns the years unit.
 515      * <p>
 516      * The months unit is not automatically normalized with the years unit.
 517      * This means that a period of "15 months" is different to a period
 518      * of "1 year and 3 months".
 519      *
 520      * @return the amount of years of this period, may be negative
 521      */
 522     public int getYears() {
 523         return years;
 524     }
 525 
 526     /**
 527      * Gets the amount of months of this period.
 528      * <p>
 529      * This returns the months unit.
 530      * <p>
 531      * The months unit is not automatically normalized with the years unit.
 532      * This means that a period of "15 months" is different to a period
 533      * of "1 year and 3 months".
 534      *
 535      * @return the amount of months of this period, may be negative
 536      */
 537     public int getMonths() {
 538         return months;
 539     }
 540 
 541     /**
 542      * Gets the amount of days of this period.
 543      * <p>
 544      * This returns the days unit.
 545      *
 546      * @return the amount of days of this period, may be negative
 547      */
 548     public int getDays() {
 549         return days;
 550     }
 551 
 552     //-----------------------------------------------------------------------
 553     /**
 554      * Returns a copy of this period with the specified amount of years.
 555      * <p>
 556      * This sets the amount of the years unit in a copy of this period.
 557      * The months and days units are unaffected.
 558      * <p>
 559      * The months unit is not automatically normalized with the years unit.
 560      * This means that a period of "15 months" is different to a period
 561      * of "1 year and 3 months".
 562      * <p>
 563      * This instance is immutable and unaffected by this method call.
 564      *
 565      * @param years  the years to represent, may be negative
 566      * @return a {@code Period} based on this period with the requested years, not null
 567      */
 568     public Period withYears(int years) {
 569         if (years == this.years) {
 570             return this;
 571         }
 572         return create(years, months, days);
 573     }
 574 
 575     /**
 576      * Returns a copy of this period with the specified amount of months.
 577      * <p>
 578      * This sets the amount of the months unit in a copy of this period.
 579      * The years and days units are unaffected.
 580      * <p>
 581      * The months unit is not automatically normalized with the years unit.
 582      * This means that a period of "15 months" is different to a period
 583      * of "1 year and 3 months".
 584      * <p>
 585      * This instance is immutable and unaffected by this method call.
 586      *
 587      * @param months  the months to represent, may be negative
 588      * @return a {@code Period} based on this period with the requested months, not null
 589      */
 590     public Period withMonths(int months) {
 591         if (months == this.months) {
 592             return this;
 593         }
 594         return create(years, months, days);
 595     }
 596 
 597     /**
 598      * Returns a copy of this period with the specified amount of days.
 599      * <p>
 600      * This sets the amount of the days unit in a copy of this period.
 601      * The years and months units are unaffected.
 602      * <p>
 603      * This instance is immutable and unaffected by this method call.
 604      *
 605      * @param days  the days to represent, may be negative
 606      * @return a {@code Period} based on this period with the requested days, not null
 607      */
 608     public Period withDays(int days) {
 609         if (days == this.days) {
 610             return this;
 611         }
 612         return create(years, months, days);
 613     }
 614 
 615     //-----------------------------------------------------------------------
 616     /**
 617      * Returns a copy of this period with the specified period added.
 618      * <p>
 619      * This operates separately on the years, months and days.
 620      * No normalization is performed.
 621      * <p>
 622      * For example, "1 year, 6 months and 3 days" plus "2 years, 2 months and 2 days"
 623      * returns "3 years, 8 months and 5 days".
 624      * <p>
 625      * The specified amount is typically an instance of {@code Period}.
 626      * Other types are interpreted using {@link Period#from(TemporalAmount)}.
 627      * <p>
 628      * This instance is immutable and unaffected by this method call.
 629      *
 630      * @param amountToAdd  the amount to add, not null
 631      * @return a {@code Period} based on this period with the requested period added, not null
 632      * @throws DateTimeException if the specified amount has a non-ISO chronology or
 633      *  contains an invalid unit
 634      * @throws ArithmeticException if numeric overflow occurs
 635      */
 636     public Period plus(TemporalAmount amountToAdd) {
 637         Period isoAmount = Period.from(amountToAdd);
 638         return create(
 639                 Math.addExact(years, isoAmount.years),
 640                 Math.addExact(months, isoAmount.months),
 641                 Math.addExact(days, isoAmount.days));
 642     }
 643 
 644     /**
 645      * Returns a copy of this period with the specified years added.
 646      * <p>
 647      * This adds the amount to the years unit in a copy of this period.
 648      * The months and days units are unaffected.
 649      * For example, "1 year, 6 months and 3 days" plus 2 years returns "3 years, 6 months and 3 days".
 650      * <p>
 651      * This instance is immutable and unaffected by this method call.
 652      *
 653      * @param yearsToAdd  the years to add, positive or negative
 654      * @return a {@code Period} based on this period with the specified years added, not null
 655      * @throws ArithmeticException if numeric overflow occurs
 656      */
 657     public Period plusYears(long yearsToAdd) {
 658         if (yearsToAdd == 0) {
 659             return this;
 660         }
 661         return create(Math.toIntExact(Math.addExact(years, yearsToAdd)), months, days);
 662     }
 663 
 664     /**
 665      * Returns a copy of this period with the specified months added.
 666      * <p>
 667      * This adds the amount to the months unit in a copy of this period.
 668      * The years and days units are unaffected.
 669      * For example, "1 year, 6 months and 3 days" plus 2 months returns "1 year, 8 months and 3 days".
 670      * <p>
 671      * This instance is immutable and unaffected by this method call.
 672      *
 673      * @param monthsToAdd  the months to add, positive or negative
 674      * @return a {@code Period} based on this period with the specified months added, not null
 675      * @throws ArithmeticException if numeric overflow occurs
 676      */
 677     public Period plusMonths(long monthsToAdd) {
 678         if (monthsToAdd == 0) {
 679             return this;
 680         }
 681         return create(years, Math.toIntExact(Math.addExact(months, monthsToAdd)), days);
 682     }
 683 
 684     /**
 685      * Returns a copy of this period with the specified days added.
 686      * <p>
 687      * This adds the amount to the days unit in a copy of this period.
 688      * The years and months units are unaffected.
 689      * For example, "1 year, 6 months and 3 days" plus 2 days returns "1 year, 6 months and 5 days".
 690      * <p>
 691      * This instance is immutable and unaffected by this method call.
 692      *
 693      * @param daysToAdd  the days to add, positive or negative
 694      * @return a {@code Period} based on this period with the specified days added, not null
 695      * @throws ArithmeticException if numeric overflow occurs
 696      */
 697     public Period plusDays(long daysToAdd) {
 698         if (daysToAdd == 0) {
 699             return this;
 700         }
 701         return create(years, months, Math.toIntExact(Math.addExact(days, daysToAdd)));
 702     }
 703 
 704     //-----------------------------------------------------------------------
 705     /**
 706      * Returns a copy of this period with the specified period subtracted.
 707      * <p>
 708      * This operates separately on the years, months and days.
 709      * No normalization is performed.
 710      * <p>
 711      * For example, "1 year, 6 months and 3 days" minus "2 years, 2 months and 2 days"
 712      * returns "-1 years, 4 months and 1 day".
 713      * <p>
 714      * The specified amount is typically an instance of {@code Period}.
 715      * Other types are interpreted using {@link Period#from(TemporalAmount)}.
 716      * <p>
 717      * This instance is immutable and unaffected by this method call.
 718      *
 719      * @param amountToSubtract  the amount to subtract, not null
 720      * @return a {@code Period} based on this period with the requested period subtracted, not null
 721      * @throws DateTimeException if the specified amount has a non-ISO chronology or
 722      *  contains an invalid unit
 723      * @throws ArithmeticException if numeric overflow occurs
 724      */
 725     public Period minus(TemporalAmount amountToSubtract) {
 726         Period isoAmount = Period.from(amountToSubtract);
 727         return create(
 728                 Math.subtractExact(years, isoAmount.years),
 729                 Math.subtractExact(months, isoAmount.months),
 730                 Math.subtractExact(days, isoAmount.days));
 731     }
 732 
 733     /**
 734      * Returns a copy of this period with the specified years subtracted.
 735      * <p>
 736      * This subtracts the amount from the years unit in a copy of this period.
 737      * The months and days units are unaffected.
 738      * For example, "1 year, 6 months and 3 days" minus 2 years returns "-1 years, 6 months and 3 days".
 739      * <p>
 740      * This instance is immutable and unaffected by this method call.
 741      *
 742      * @param yearsToSubtract  the years to subtract, positive or negative
 743      * @return a {@code Period} based on this period with the specified years subtracted, not null
 744      * @throws ArithmeticException if numeric overflow occurs
 745      */
 746     public Period minusYears(long yearsToSubtract) {
 747         return (yearsToSubtract == Long.MIN_VALUE ? plusYears(Long.MAX_VALUE).plusYears(1) : plusYears(-yearsToSubtract));
 748     }
 749 
 750     /**
 751      * Returns a copy of this period with the specified months subtracted.
 752      * <p>
 753      * This subtracts the amount from the months unit in a copy of this period.
 754      * The years and days units are unaffected.
 755      * For example, "1 year, 6 months and 3 days" minus 2 months returns "1 year, 4 months and 3 days".
 756      * <p>
 757      * This instance is immutable and unaffected by this method call.
 758      *
 759      * @param monthsToSubtract  the years to subtract, positive or negative
 760      * @return a {@code Period} based on this period with the specified months subtracted, not null
 761      * @throws ArithmeticException if numeric overflow occurs
 762      */
 763     public Period minusMonths(long monthsToSubtract) {
 764         return (monthsToSubtract == Long.MIN_VALUE ? plusMonths(Long.MAX_VALUE).plusMonths(1) : plusMonths(-monthsToSubtract));
 765     }
 766 
 767     /**
 768      * Returns a copy of this period with the specified days subtracted.
 769      * <p>
 770      * This subtracts the amount from the days unit in a copy of this period.
 771      * The years and months units are unaffected.
 772      * For example, "1 year, 6 months and 3 days" minus 2 days returns "1 year, 6 months and 1 day".
 773      * <p>
 774      * This instance is immutable and unaffected by this method call.
 775      *
 776      * @param daysToSubtract  the months to subtract, positive or negative
 777      * @return a {@code Period} based on this period with the specified days subtracted, not null
 778      * @throws ArithmeticException if numeric overflow occurs
 779      */
 780     public Period minusDays(long daysToSubtract) {
 781         return (daysToSubtract == Long.MIN_VALUE ? plusDays(Long.MAX_VALUE).plusDays(1) : plusDays(-daysToSubtract));
 782     }
 783 
 784     //-----------------------------------------------------------------------
 785     /**
 786      * Returns a new instance with each element in this period multiplied
 787      * by the specified scalar.
 788      * <p>
 789      * This returns a period with each of the years, months and days units
 790      * individually multiplied.
 791      * For example, a period of "2 years, -3 months and 4 days" multiplied by
 792      * 3 will return "6 years, -9 months and 12 days".
 793      * No normalization is performed.
 794      *
 795      * @param scalar  the scalar to multiply by, not null
 796      * @return a {@code Period} based on this period with the amounts multiplied by the scalar, not null
 797      * @throws ArithmeticException if numeric overflow occurs
 798      */
 799     public Period multipliedBy(int scalar) {
 800         if (this == ZERO || scalar == 1) {
 801             return this;
 802         }
 803         return create(
 804                 Math.multiplyExact(years, scalar),
 805                 Math.multiplyExact(months, scalar),
 806                 Math.multiplyExact(days, scalar));
 807     }
 808 
 809     /**
 810      * Returns a new instance with each amount in this period negated.
 811      * <p>
 812      * This returns a period with each of the years, months and days units
 813      * individually negated.
 814      * For example, a period of "2 years, -3 months and 4 days" will be
 815      * negated to "-2 years, 3 months and -4 days".
 816      * No normalization is performed.
 817      *
 818      * @return a {@code Period} based on this period with the amounts negated, not null
 819      * @throws ArithmeticException if numeric overflow occurs, which only happens if
 820      *  one of the units has the value {@code Integer.MIN_VALUE}
 821      */
 822     public Period negated() {
 823         return multipliedBy(-1);
 824     }
 825 
 826     //-----------------------------------------------------------------------
 827     /**
 828      * Returns a copy of this period with the years and months normalized.
 829      * <p>
 830      * This normalizes the years and months units, leaving the days unit unchanged.
 831      * The months unit is adjusted to have an absolute value less than 12,
 832      * with the years unit being adjusted to compensate. For example, a period of
 833      * "1 Year and 15 months" will be normalized to "2 years and 3 months".
 834      * <p>
 835      * The sign of the years and months units will be the same after normalization.
 836      * For example, a period of "1 year and -25 months" will be normalized to
 837      * "-1 year and -1 month".
 838      * <p>
 839      * This instance is immutable and unaffected by this method call.
 840      *
 841      * @return a {@code Period} based on this period with excess months normalized to years, not null
 842      * @throws ArithmeticException if numeric overflow occurs
 843      */
 844     public Period normalized() {
 845         long totalMonths = toTotalMonths();
 846         long splitYears = totalMonths / 12;
 847         int splitMonths = (int) (totalMonths % 12);  // no overflow
 848         if (splitYears == years && splitMonths == months) {
 849             return this;
 850         }
 851         return create(Math.toIntExact(splitYears), splitMonths, days);
 852     }
 853 
 854     /**
 855      * Gets the total number of months in this period.
 856      * <p>
 857      * This returns the total number of months in the period by multiplying the
 858      * number of years by 12 and adding the number of months.
 859      * <p>
 860      * This instance is immutable and unaffected by this method call.
 861      *
 862      * @return the total number of months in the period, may be negative
 863      */
 864     public long toTotalMonths() {
 865         return years * 12L + months;  // no overflow
 866     }
 867 
 868     //-------------------------------------------------------------------------
 869     /**
 870      * Adds this period to the specified temporal object.
 871      * <p>
 872      * This returns a temporal object of the same observable type as the input
 873      * with this period added.
 874      * If the temporal has a chronology, it must be the ISO chronology.
 875      * <p>
 876      * In most cases, it is clearer to reverse the calling pattern by using
 877      * {@link Temporal#plus(TemporalAmount)}.
 878      * <pre>
 879      *   // these two lines are equivalent, but the second approach is recommended
 880      *   dateTime = thisPeriod.addTo(dateTime);
 881      *   dateTime = dateTime.plus(thisPeriod);
 882      * </pre>
 883      * <p>
 884      * The calculation operates as follows.
 885      * First, the chronology of the temporal is checked to ensure it is ISO chronology or null.
 886      * Second, if the months are zero, the years are added if non-zero, otherwise
 887      * the combination of years and months is added if non-zero.
 888      * Finally, any days are added.
 889      * <p>
 890      * This approach ensures that a partial period can be added to a partial date.
 891      * For example, a period of years and/or months can be added to a {@code YearMonth},
 892      * but a period including days cannot.
 893      * The approach also adds years and months together when necessary, which ensures
 894      * correct behaviour at the end of the month.
 895      * <p>
 896      * This instance is immutable and unaffected by this method call.
 897      *
 898      * @param temporal  the temporal object to adjust, not null
 899      * @return an object of the same type with the adjustment made, not null
 900      * @throws DateTimeException if unable to add
 901      * @throws ArithmeticException if numeric overflow occurs
 902      */
 903     @Override
 904     public Temporal addTo(Temporal temporal) {
 905         validateChrono(temporal);
 906         if (months == 0) {
 907             if (years != 0) {
 908                 temporal = temporal.plus(years, YEARS);
 909             }
 910         } else {
 911             long totalMonths = toTotalMonths();
 912             if (totalMonths != 0) {
 913                 temporal = temporal.plus(totalMonths, MONTHS);
 914             }
 915         }
 916         if (days != 0) {
 917             temporal = temporal.plus(days, DAYS);
 918         }
 919         return temporal;
 920     }
 921 
 922     /**
 923      * Subtracts this period from the specified temporal object.
 924      * <p>
 925      * This returns a temporal object of the same observable type as the input
 926      * with this period subtracted.
 927      * If the temporal has a chronology, it must be the ISO chronology.
 928      * <p>
 929      * In most cases, it is clearer to reverse the calling pattern by using
 930      * {@link Temporal#minus(TemporalAmount)}.
 931      * <pre>
 932      *   // these two lines are equivalent, but the second approach is recommended
 933      *   dateTime = thisPeriod.subtractFrom(dateTime);
 934      *   dateTime = dateTime.minus(thisPeriod);
 935      * </pre>
 936      * <p>
 937      * The calculation operates as follows.
 938      * First, the chronology of the temporal is checked to ensure it is ISO chronology or null.
 939      * Second, if the months are zero, the years are subtracted if non-zero, otherwise
 940      * the combination of years and months is subtracted if non-zero.
 941      * Finally, any days are subtracted.
 942      * <p>
 943      * This approach ensures that a partial period can be subtracted from a partial date.
 944      * For example, a period of years and/or months can be subtracted from a {@code YearMonth},
 945      * but a period including days cannot.
 946      * The approach also subtracts years and months together when necessary, which ensures
 947      * correct behaviour at the end of the month.
 948      * <p>
 949      * This instance is immutable and unaffected by this method call.
 950      *
 951      * @param temporal  the temporal object to adjust, not null
 952      * @return an object of the same type with the adjustment made, not null
 953      * @throws DateTimeException if unable to subtract
 954      * @throws ArithmeticException if numeric overflow occurs
 955      */
 956     @Override
 957     public Temporal subtractFrom(Temporal temporal) {
 958         validateChrono(temporal);
 959         if (months == 0) {
 960             if (years != 0) {
 961                 temporal = temporal.minus(years, YEARS);
 962             }
 963         } else {
 964             long totalMonths = toTotalMonths();
 965             if (totalMonths != 0) {
 966                 temporal = temporal.minus(totalMonths, MONTHS);
 967             }
 968         }
 969         if (days != 0) {
 970             temporal = temporal.minus(days, DAYS);
 971         }
 972         return temporal;
 973     }
 974 
 975     /**
 976      * Validates that the temporal has the correct chronology.
 977      */
 978     private void validateChrono(TemporalAccessor temporal) {
 979         Objects.requireNonNull(temporal, "temporal");
 980         Chronology temporalChrono = temporal.query(TemporalQueries.chronology());
 981         if (temporalChrono != null && IsoChronology.INSTANCE.equals(temporalChrono) == false) {
 982             throw new DateTimeException("Chronology mismatch, expected: ISO, actual: " + temporalChrono.getId());
 983         }
 984     }
 985 
 986     //-----------------------------------------------------------------------
 987     /**
 988      * Checks if this period is equal to another period.
 989      * <p>
 990      * The comparison is based on the type {@code Period} and each of the three amounts.
 991      * To be equal, the years, months and days units must be individually equal.
 992      * Note that this means that a period of "15 Months" is not equal to a period
 993      * of "1 Year and 3 Months".
 994      *
 995      * @param obj  the object to check, null returns false
 996      * @return true if this is equal to the other period
 997      */
 998     @Override
 999     public boolean equals(Object obj) {
1000         if (this == obj) {
1001             return true;
1002         }
1003         return (obj instanceof Period other)
1004                 && years == other.years
1005                 && months == other.months
1006                 && days == other.days;
1007     }
1008 
1009     /**
1010      * A hash code for this period.
1011      *
1012      * @return a suitable hash code
1013      */
1014     @Override
1015     public int hashCode() {
1016         return years + Integer.rotateLeft(months, 8) + Integer.rotateLeft(days, 16);
1017     }
1018 
1019     //-----------------------------------------------------------------------
1020     /**
1021      * Outputs this period as a {@code String}, such as {@code P6Y3M1D}.
1022      * <p>
1023      * The output will be in the ISO-8601 period format.
1024      * A zero period will be represented as zero days, 'P0D'.
1025      *
1026      * @return a string representation of this period, not null
1027      */
1028     @Override
1029     public String toString() {
1030         if (this == ZERO) {
1031             return "P0D";
1032         } else {
1033             StringBuilder buf = new StringBuilder();
1034             buf.append('P');
1035             if (years != 0) {
1036                 buf.append(years).append('Y');
1037             }
1038             if (months != 0) {
1039                 buf.append(months).append('M');
1040             }
1041             if (days != 0) {
1042                 buf.append(days).append('D');
1043             }
1044             return buf.toString();
1045         }
1046     }
1047 
1048     //-----------------------------------------------------------------------
1049     /**
1050      * Writes the object using a
1051      * <a href="{@docRoot}/serialized-form.html#java.time.Ser">dedicated serialized form</a>.
1052      * @serialData
1053      * <pre>
1054      *  out.writeByte(14);  // identifies a Period
1055      *  out.writeInt(years);
1056      *  out.writeInt(months);
1057      *  out.writeInt(days);
1058      * </pre>
1059      *
1060      * @return the instance of {@code Ser}, not null
1061      */
1062     @java.io.Serial
1063     private Object writeReplace() {
1064         return new Ser(Ser.PERIOD_TYPE, this);
1065     }
1066 
1067     /**
1068      * Defend against malicious streams.
1069      *
1070      * @param s the stream to read
1071      * @throws java.io.InvalidObjectException always
1072      */
1073     @java.io.Serial
1074     private void readObject(ObjectInputStream s) throws InvalidObjectException {
1075         throw new InvalidObjectException("Deserialization via serialization delegate");
1076     }
1077 
1078     void writeExternal(DataOutput out) throws IOException {
1079         out.writeInt(years);
1080         out.writeInt(months);
1081         out.writeInt(days);
1082     }
1083 
1084     static Period readExternal(DataInput in) throws IOException {
1085         int years = in.readInt();
1086         int months = in.readInt();
1087         int days = in.readInt();
1088         return Period.of(years, months, days);
1089     }
1090 
1091 }