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