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