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