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