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