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.temporal; 63 64 import static java.time.temporal.ChronoField.ERA; 65 import static java.time.temporal.ChronoField.YEAR; 66 import static java.time.temporal.ChronoField.YEAR_OF_ERA; 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.Clock; 76 import java.time.DateTimeException; 77 import java.time.LocalDate; 78 import java.time.Month; 79 import java.time.ZoneId; 80 import java.time.format.DateTimeFormatter; 81 import java.time.format.DateTimeFormatterBuilder; 82 import java.time.format.DateTimeParseException; 83 import java.time.format.SignStyle; 84 import java.util.Objects; 85 86 /** 87 * A year in the ISO-8601 calendar system, such as {@code 2007}. 88 * <p> 89 * {@code Year} is an immutable date-time object that represents a year. 90 * Any field that can be derived from a year can be obtained. 91 * <p> 92 * <b>Note that years in the ISO chronology only align with years in the 93 * Gregorian-Julian system for modern years. Parts of Russia did not switch to the 94 * modern Gregorian/ISO rules until 1920. 95 * As such, historical years must be treated with caution.</b> 96 * <p> 97 * This class does not store or represent a month, day, time or time-zone. 98 * For example, the value "2007" can be stored in a {@code Year}. 99 * <p> 100 * Years represented by this class follow the ISO-8601 standard and use 101 * the proleptic numbering system. Year 1 is preceded by year 0, then by year -1. 102 * <p> 103 * The ISO-8601 calendar system is the modern civil calendar system used today 194 * This method accepts a year value from the proleptic ISO calendar system. 195 * <p> 196 * The year 2AD/CE is represented by 2.<br> 197 * The year 1AD/CE is represented by 1.<br> 198 * The year 1BC/BCE is represented by 0.<br> 199 * The year 2BC/BCE is represented by -1.<br> 200 * 201 * @param isoYear the ISO proleptic year to represent, from {@code MIN_VALUE} to {@code MAX_VALUE} 202 * @return the year, not null 203 * @throws DateTimeException if the field is invalid 204 */ 205 public static Year of(int isoYear) { 206 YEAR.checkValidValue(isoYear); 207 return new Year(isoYear); 208 } 209 210 //----------------------------------------------------------------------- 211 /** 212 * Obtains an instance of {@code Year} from a temporal object. 213 * <p> 214 * A {@code TemporalAccessor} represents some form of date and time information. 215 * This factory converts the arbitrary temporal object to an instance of {@code Year}. 216 * <p> 217 * The conversion extracts the {@link ChronoField#YEAR year} field. 218 * The extraction is only permitted if the temporal object has an ISO 219 * chronology, or can be converted to a {@code LocalDate}. 220 * <p> 221 * This method matches the signature of the functional interface {@link TemporalQuery} 222 * allowing it to be used in queries via method reference, {@code Year::from}. 223 * 224 * @param temporal the temporal object to convert, not null 225 * @return the year, not null 226 * @throws DateTimeException if unable to convert to a {@code Year} 227 */ 228 public static Year from(TemporalAccessor temporal) { 229 if (temporal instanceof Year) { 230 return (Year) temporal; 231 } 232 try { 233 if (ISOChrono.INSTANCE.equals(Chrono.from(temporal)) == false) { 234 temporal = LocalDate.from(temporal); 235 } 236 return of(temporal.get(YEAR)); 237 } catch (DateTimeException ex) { 238 throw new DateTimeException("Unable to obtain Year from TemporalAccessor: " + temporal.getClass(), ex); 239 } 240 } 241 242 //----------------------------------------------------------------------- 243 /** 244 * Obtains an instance of {@code Year} from a text string such as {@code 2007}. 245 * <p> 246 * The string must represent a valid year. 247 * Years outside the range 0000 to 9999 must be prefixed by the plus or minus symbol. 248 * 249 * @param text the text to parse such as "2007", not null 250 * @return the parsed year, not null 251 * @throws DateTimeParseException if the text cannot be parsed 252 */ 253 public static Year parse(CharSequence text) { 307 /** 308 * Gets the year value. 309 * <p> 310 * The year returned by this method is proleptic as per {@code get(YEAR)}. 311 * 312 * @return the year, {@code MIN_VALUE} to {@code MAX_VALUE} 313 */ 314 public int getValue() { 315 return year; 316 } 317 318 //----------------------------------------------------------------------- 319 /** 320 * Checks if the specified field is supported. 321 * <p> 322 * This checks if this year can be queried for the specified field. 323 * If false, then calling the {@link #range(TemporalField) range} and 324 * {@link #get(TemporalField) get} methods will throw an exception. 325 * <p> 326 * If the field is a {@link ChronoField} then the query is implemented here. 327 * The {@link #isSupported(TemporalField) supported fields} will return valid 328 * values based on this date-time. 329 * The supported fields are: 330 * <ul> 331 * <li>{@code YEAR_OF_ERA} 332 * <li>{@code YEAR} 333 * <li>{@code ERA} 334 * </ul> 335 * All other {@code ChronoField} instances will return false. 336 * <p> 337 * If the field is not a {@code ChronoField}, then the result of this method 338 * is obtained by invoking {@code TemporalField.doIsSupported(TemporalAccessor)} 339 * passing {@code this} as the argument. 340 * Whether the field is supported is determined by the field. 341 * 342 * @param field the field to check, null returns false 343 * @return true if the field is supported on this year, false if not 344 */ 345 @Override 346 public boolean isSupported(TemporalField field) { 347 if (field instanceof ChronoField) { 348 return field == YEAR || field == YEAR_OF_ERA || field == ERA; 349 } 350 return field != null && field.doIsSupported(this); 351 } 352 353 /** 354 * Gets the range of valid values for the specified field. 355 * <p> 356 * The range object expresses the minimum and maximum valid values for a field. 357 * This year is used to enhance the accuracy of the returned range. 358 * If it is not possible to return the range, because the field is not supported 359 * or for some other reason, an exception is thrown. 360 * <p> 361 * If the field is a {@link ChronoField} then the query is implemented here. 362 * The {@link #isSupported(TemporalField) supported fields} will return 363 * appropriate range instances. 364 * All other {@code ChronoField} instances will throw a {@code DateTimeException}. 365 * <p> 366 * If the field is not a {@code ChronoField}, then the result of this method 367 * is obtained by invoking {@code TemporalField.doRange(TemporalAccessor)} 368 * passing {@code this} as the argument. 369 * Whether the range can be obtained is determined by the field. 370 * 371 * @param field the field to query the range for, not null 372 * @return the range of valid values for the field, not null 373 * @throws DateTimeException if the range for the field cannot be obtained 374 */ 375 @Override 376 public ValueRange range(TemporalField field) { 377 if (field == YEAR_OF_ERA) { 378 return (year <= 0 ? ValueRange.of(1, MAX_VALUE + 1) : ValueRange.of(1, MAX_VALUE)); 379 } 380 return Temporal.super.range(field); 381 } 382 383 /** 384 * Gets the value of the specified field from this year as an {@code int}. 385 * <p> 386 * This queries this year for the value for the specified field. 387 * The returned value will always be within the valid range of values for the field. 388 * If it is not possible to return the value, because the field is not supported 389 * or for some other reason, an exception is thrown. 390 * <p> 391 * If the field is a {@link ChronoField} then the query is implemented here. 392 * The {@link #isSupported(TemporalField) supported fields} will return valid 393 * values based on this year. 394 * All other {@code ChronoField} instances will throw a {@code DateTimeException}. 395 * <p> 396 * If the field is not a {@code ChronoField}, then the result of this method 397 * is obtained by invoking {@code TemporalField.doGet(TemporalAccessor)} 398 * passing {@code this} as the argument. Whether the value can be obtained, 399 * and what the value represents, is determined by the field. 400 * 401 * @param field the field to get, not null 402 * @return the value for the field 403 * @throws DateTimeException if a value for the field cannot be obtained 404 * @throws ArithmeticException if numeric overflow occurs 405 */ 406 @Override // override for Javadoc 407 public int get(TemporalField field) { 408 return range(field).checkValidIntValue(getLong(field), field); 409 } 410 411 /** 412 * Gets the value of the specified field from this year as a {@code long}. 413 * <p> 414 * This queries this year for the value for the specified field. 415 * If it is not possible to return the value, because the field is not supported 416 * or for some other reason, an exception is thrown. 417 * <p> 418 * If the field is a {@link ChronoField} then the query is implemented here. 419 * The {@link #isSupported(TemporalField) supported fields} will return valid 420 * values based on this year. 421 * All other {@code ChronoField} instances will throw a {@code DateTimeException}. 422 * <p> 423 * If the field is not a {@code ChronoField}, then the result of this method 424 * is obtained by invoking {@code TemporalField.doGet(TemporalAccessor)} 425 * passing {@code this} as the argument. Whether the value can be obtained, 426 * and what the value represents, is determined by the field. 427 * 428 * @param field the field to get, not null 429 * @return the value for the field 430 * @throws DateTimeException if a value for the field cannot be obtained 431 * @throws ArithmeticException if numeric overflow occurs 432 */ 433 @Override 434 public long getLong(TemporalField field) { 435 if (field instanceof ChronoField) { 436 switch ((ChronoField) field) { 437 case YEAR_OF_ERA: return (year < 1 ? 1 - year : year); 438 case YEAR: return year; 439 case ERA: return (year < 1 ? 0 : 1); 440 } 441 throw new DateTimeException("Unsupported field: " + field.getName()); 442 } 443 return field.doGet(this); 444 } 445 446 //----------------------------------------------------------------------- 447 /** 448 * Checks if the year is a leap year, according to the ISO proleptic 449 * calendar system rules. 450 * <p> 451 * This method applies the current rules for leap years across the whole time-line. 452 * In general, a year is a leap year if it is divisible by four without 453 * remainder. However, years divisible by 100, are not leap years, with 454 * the exception of years divisible by 400 which are. 455 * <p> 456 * For example, 1904 is a leap year it is divisible by 4. 457 * 1900 was not a leap year as it is divisible by 100, however 2000 was a 458 * leap year as it is divisible by 400. 459 * <p> 460 * The calculation is proleptic - applying the same rules into the far future and far past. 461 * This is historically inaccurate, but is correct for the ISO-8601 standard. 462 * 463 * @return true if the year is leap, false otherwise 475 * @param monthDay the month-day to validate, null returns false 476 * @return true if the month and day are valid for this year 477 */ 478 public boolean isValidMonthDay(MonthDay monthDay) { 479 return monthDay != null && monthDay.isValidYear(year); 480 } 481 482 /** 483 * Gets the length of this year in days. 484 * 485 * @return the length of this year in days, 365 or 366 486 */ 487 public int length() { 488 return isLeap() ? 366 : 365; 489 } 490 491 //----------------------------------------------------------------------- 492 /** 493 * Returns an adjusted copy of this year. 494 * <p> 495 * This returns a new {@code Year}, based on this one, with the year adjusted. 496 * The adjustment takes place using the specified adjuster strategy object. 497 * Read the documentation of the adjuster to understand what adjustment will be made. 498 * <p> 499 * The result of this method is obtained by invoking the 500 * {@link TemporalAdjuster#adjustInto(Temporal)} method on the 501 * specified adjuster passing {@code this} as the argument. 502 * <p> 503 * This instance is immutable and unaffected by this method call. 504 * 505 * @param adjuster the adjuster to use, not null 506 * @return a {@code Year} based on {@code this} with the adjustment made, not null 507 * @throws DateTimeException if the adjustment cannot be made 508 * @throws ArithmeticException if numeric overflow occurs 509 */ 510 @Override 511 public Year with(TemporalAdjuster adjuster) { 512 return (Year) adjuster.adjustInto(this); 513 } 514 515 /** 516 * Returns a copy of this year with the specified field set to a new value. 517 * <p> 518 * This returns a new {@code Year}, based on this one, with the value 519 * for the specified field changed. 520 * If it is not possible to set the value, because the field is not supported or for 521 * some other reason, an exception is thrown. 522 * <p> 523 * If the field is a {@link ChronoField} then the adjustment is implemented here. 524 * The supported fields behave as follows: 525 * <ul> 526 * <li>{@code YEAR_OF_ERA} - 527 * Returns a {@code Year} with the specified year-of-era 528 * The era will be unchanged. 529 * <li>{@code YEAR} - 530 * Returns a {@code Year} with the specified year. 531 * This completely replaces the date and is equivalent to {@link #of(int)}. 532 * <li>{@code ERA} - 533 * Returns a {@code Year} with the specified era. 534 * The year-of-era will be unchanged. 535 * </ul> 536 * <p> 537 * In all cases, if the new value is outside the valid range of values for the field 538 * then a {@code DateTimeException} will be thrown. 539 * <p> 540 * All other {@code ChronoField} instances will throw a {@code DateTimeException}. 541 * <p> 542 * If the field is not a {@code ChronoField}, then the result of this method 543 * is obtained by invoking {@code TemporalField.doWith(Temporal, long)} 544 * passing {@code this} as the argument. In this case, the field determines 545 * whether and how to adjust the instant. 546 * <p> 547 * This instance is immutable and unaffected by this method call. 548 * 549 * @param field the field to set in the result, not null 550 * @param newValue the new value of the field in the result 551 * @return a {@code Year} based on {@code this} with the specified field set, not null 552 * @throws DateTimeException if the field cannot be set 553 * @throws ArithmeticException if numeric overflow occurs 554 */ 555 @Override 556 public Year with(TemporalField field, long newValue) { 557 if (field instanceof ChronoField) { 558 ChronoField f = (ChronoField) field; 559 f.checkValidValue(newValue); 560 switch (f) { 561 case YEAR_OF_ERA: return Year.of((int) (year < 1 ? 1 - newValue : newValue)); 562 case YEAR: return Year.of((int) newValue); 563 case ERA: return (getLong(ERA) == newValue ? this : Year.of(1 - year)); 564 } 565 throw new DateTimeException("Unsupported field: " + field.getName()); 566 } 567 return field.doWith(this, newValue); 568 } 569 570 //----------------------------------------------------------------------- 571 /** 572 * Returns a copy of this year with the specified period added. 573 * <p> 574 * This method returns a new year based on this year with the specified period added. 575 * The adder is typically {@link java.time.Period} but may be any other type implementing 576 * the {@link TemporalAdder} interface. 577 * The calculation is delegated to the specified adjuster, which typically calls 578 * back to {@link #plus(long, TemporalUnit)}. 579 * <p> 580 * This instance is immutable and unaffected by this method call. 581 * 582 * @param adder the adder to use, not null 583 * @return a {@code Year} based on this year with the addition made, not null 584 * @throws DateTimeException if the addition cannot be made 585 * @throws ArithmeticException if numeric overflow occurs 586 */ 587 @Override 588 public Year plus(TemporalAdder adder) { 589 return (Year) adder.addTo(this); 590 } 591 592 /** 593 * {@inheritDoc} 594 * @throws DateTimeException {@inheritDoc} 595 * @throws ArithmeticException {@inheritDoc} 596 */ 597 @Override 598 public Year plus(long amountToAdd, TemporalUnit unit) { 599 if (unit instanceof ChronoUnit) { 600 switch ((ChronoUnit) unit) { 601 case YEARS: return plusYears(amountToAdd); 602 case DECADES: return plusYears(Math.multiplyExact(amountToAdd, 10)); 603 case CENTURIES: return plusYears(Math.multiplyExact(amountToAdd, 100)); 604 case MILLENNIA: return plusYears(Math.multiplyExact(amountToAdd, 1000)); 605 case ERAS: return with(ERA, Math.addExact(getLong(ERA), amountToAdd)); 606 } 607 throw new DateTimeException("Unsupported unit: " + unit.getName()); 608 } 609 return unit.doPlus(this, amountToAdd); 610 } 611 612 /** 613 * Returns a copy of this year with the specified number of years added. 614 * <p> 615 * This instance is immutable and unaffected by this method call. 616 * 617 * @param yearsToAdd the years to add, may be negative 618 * @return a {@code Year} based on this year with the period added, not null 619 * @throws DateTimeException if the result exceeds the supported year range 620 */ 621 public Year plusYears(long yearsToAdd) { 622 if (yearsToAdd == 0) { 623 return this; 624 } 625 return of(YEAR.checkValidIntValue(year + yearsToAdd)); // overflow safe 626 } 627 628 //----------------------------------------------------------------------- 629 /** 630 * Returns a copy of this year with the specified period subtracted. 631 * <p> 632 * This method returns a new year based on this year with the specified period subtracted. 633 * The subtractor is typically {@link java.time.Period} but may be any other type implementing 634 * the {@link TemporalSubtractor} interface. 635 * The calculation is delegated to the specified adjuster, which typically calls 636 * back to {@link #minus(long, TemporalUnit)}. 637 * <p> 638 * This instance is immutable and unaffected by this method call. 639 * 640 * @param subtractor the subtractor to use, not null 641 * @return a {@code Year} based on this year with the subtraction made, not null 642 * @throws DateTimeException if the subtraction cannot be made 643 * @throws ArithmeticException if numeric overflow occurs 644 */ 645 @Override 646 public Year minus(TemporalSubtractor subtractor) { 647 return (Year) subtractor.subtractFrom(this); 648 } 649 650 /** 651 * {@inheritDoc} 652 * @throws DateTimeException {@inheritDoc} 653 * @throws ArithmeticException {@inheritDoc} 654 */ 655 @Override 656 public Year minus(long amountToSubtract, TemporalUnit unit) { 657 return (amountToSubtract == Long.MIN_VALUE ? plus(Long.MAX_VALUE, unit).plus(1, unit) : plus(-amountToSubtract, unit)); 658 } 659 660 /** 661 * Returns a copy of this year with the specified number of years subtracted. 662 * <p> 663 * This instance is immutable and unaffected by this method call. 664 * 665 * @param yearsToSubtract the years to subtract, may be negative 666 * @return a {@code Year} based on this year with the period subtracted, not null 667 * @throws DateTimeException if the result exceeds the supported year range 668 */ 669 public Year minusYears(long yearsToSubtract) { 670 return (yearsToSubtract == Long.MIN_VALUE ? plusYears(Long.MAX_VALUE).plusYears(1) : plusYears(-yearsToSubtract)); 671 } 672 673 //----------------------------------------------------------------------- 675 * Queries this year using the specified query. 676 * <p> 677 * This queries this year using the specified query strategy object. 678 * The {@code TemporalQuery} object defines the logic to be used to 679 * obtain the result. Read the documentation of the query to understand 680 * what the result of this method will be. 681 * <p> 682 * The result of this method is obtained by invoking the 683 * {@link TemporalQuery#queryFrom(TemporalAccessor)} method on the 684 * specified query passing {@code this} as the argument. 685 * 686 * @param <R> the type of the result 687 * @param query the query to invoke, not null 688 * @return the query result, null may be returned (defined by the query) 689 * @throws DateTimeException if unable to query (defined by the query) 690 * @throws ArithmeticException if numeric overflow occurs (defined by the query) 691 */ 692 @SuppressWarnings("unchecked") 693 @Override 694 public <R> R query(TemporalQuery<R> query) { 695 if (query == Queries.chrono()) { 696 return (R) ISOChrono.INSTANCE; 697 } else if (query == Queries.precision()) { 698 return (R) YEARS; 699 } 700 return Temporal.super.query(query); 701 } 702 703 /** 704 * Adjusts the specified temporal object to have this year. 705 * <p> 706 * This returns a temporal object of the same observable type as the input 707 * with the year changed to be the same as this. 708 * <p> 709 * The adjustment is equivalent to using {@link Temporal#with(TemporalField, long)} 710 * passing {@link ChronoField#YEAR} as the field. 711 * If the specified temporal object does not use the ISO calendar system then 712 * a {@code DateTimeException} is thrown. 713 * <p> 714 * In most cases, it is clearer to reverse the calling pattern by using 715 * {@link Temporal#with(TemporalAdjuster)}: 716 * <pre> 717 * // these two lines are equivalent, but the second approach is recommended 718 * temporal = thisYear.adjustInto(temporal); 719 * temporal = temporal.with(thisYear); 720 * </pre> 721 * <p> 722 * This instance is immutable and unaffected by this method call. 723 * 724 * @param temporal the target object to be adjusted, not null 725 * @return the adjusted object, not null 726 * @throws DateTimeException if unable to make the adjustment 727 * @throws ArithmeticException if numeric overflow occurs 728 */ 729 @Override 730 public Temporal adjustInto(Temporal temporal) { 731 if (Chrono.from(temporal).equals(ISOChrono.INSTANCE) == false) { 732 throw new DateTimeException("Adjustment only supported on ISO date-time"); 733 } 734 return temporal.with(YEAR, year); 735 } 736 737 /** 738 * Calculates the period between this year and another year in 739 * terms of the specified unit. 740 * <p> 741 * This calculates the period between two years in terms of a single unit. 742 * The start and end points are {@code this} and the specified year. 743 * The result will be negative if the end is before the start. 744 * The {@code Temporal} passed to this method must be a {@code Year}. 745 * For example, the period in decades between two year can be calculated 746 * using {@code startYear.periodUntil(endYear, DECADES)}. 747 * <p> 748 * The calculation returns a whole number, representing the number of 749 * complete units between the two years. 750 * For example, the period in decades between 2012 and 2031 751 * will only be one decade as it is one year short of two decades. 752 * <p> 753 * This method operates in association with {@link TemporalUnit#between}. 754 * The result of this method is a {@code long} representing the amount of 755 * the specified unit. By contrast, the result of {@code between} is an 756 * object that can be used directly in addition/subtraction: 757 * <pre> 758 * long period = start.periodUntil(end, YEARS); // this method 759 * dateTime.plus(YEARS.between(start, end)); // use in plus/minus 760 * </pre> 761 * <p> 762 * The calculation is implemented in this method for {@link ChronoUnit}. 763 * The units {@code YEARS}, {@code DECADES}, {@code CENTURIES}, 764 * {@code MILLENNIA} and {@code ERAS} are supported. 765 * Other {@code ChronoUnit} values will throw an exception. 766 * <p> 767 * If the unit is not a {@code ChronoUnit}, then the result of this method 768 * is obtained by invoking {@code TemporalUnit.between(Temporal, Temporal)} 769 * passing {@code this} as the first argument and the input temporal as 770 * the second argument. 771 * <p> 772 * This instance is immutable and unaffected by this method call. 773 * 774 * @param endYear the end year, which must be a {@code Year}, not null 775 * @param unit the unit to measure the period in, not null 776 * @return the amount of the period between this year and the end year 777 * @throws DateTimeException if the period cannot be calculated 778 * @throws ArithmeticException if numeric overflow occurs 779 */ 780 @Override 781 public long periodUntil(Temporal endYear, TemporalUnit unit) { 782 if (endYear instanceof Year == false) { 783 Objects.requireNonNull(endYear, "endYear"); 784 throw new DateTimeException("Unable to calculate period between objects of two different types"); 785 } 786 Year end = (Year) endYear; 787 if (unit instanceof ChronoUnit) { 788 long yearsUntil = ((long) end.year) - year; // no overflow 789 switch ((ChronoUnit) unit) { 790 case YEARS: return yearsUntil; 791 case DECADES: return yearsUntil / 10; 792 case CENTURIES: return yearsUntil / 100; 793 case MILLENNIA: return yearsUntil / 1000; 794 case ERAS: return end.getLong(ERA) - getLong(ERA); 795 } 796 throw new DateTimeException("Unsupported unit: " + unit.getName()); 797 } 798 return unit.between(this, endYear).getAmount(); 799 } 800 801 //----------------------------------------------------------------------- 802 /** 803 * Returns a date formed from this year at the specified day-of-year. 804 * <p> 805 * This combines this year and the specified day-of-year to form a {@code LocalDate}. 806 * The day-of-year value 366 is only valid in a leap year. 807 * <p> 808 * This instance is immutable and unaffected by this method call. 809 * 810 * @param dayOfYear the day-of-year to use, not null 811 * @return the local date formed from this year and the specified date of year, not null 812 * @throws DateTimeException if the day of year is 366 and this is not a leap year 813 */ 814 public LocalDate atDay(int dayOfYear) { 815 return LocalDate.ofYearDay(year, dayOfYear); 816 } 817 818 /** 819 * Returns a year-month formed from this year at the specified month. 820 * <p> 821 * This combines this year and the specified month to form a {@code YearMonth}. 822 * All possible combinations of year and month are valid. 823 * <p> 824 * This method can be used as part of a chain to produce a date: 825 * <pre> 826 * LocalDate date = year.atMonth(month).atDay(day); 827 * </pre> 828 * <p> 829 * This instance is immutable and unaffected by this method call. 830 * 831 * @param month the month-of-year to use, not null 832 * @return the year-month formed from this year and the specified month, not null 833 */ 834 public YearMonth atMonth(Month month) { 835 return YearMonth.of(year, month); 836 } 837 838 /** 839 * Returns a year-month formed from this year at the specified month. 840 * <p> 841 * This combines this year and the specified month to form a {@code YearMonth}. 842 * All possible combinations of year and month are valid. 843 * <p> 844 * This method can be used as part of a chain to produce a date: 845 * <pre> 846 * LocalDate date = year.atMonth(month).atDay(day); 847 * </pre> 848 * <p> 849 * This instance is immutable and unaffected by this method call. 850 * 851 * @param month the month-of-year to use, from 1 (January) to 12 (December) 852 * @return the year-month formed from this year and the specified month, not null 853 */ 854 public YearMonth atMonth(int month) { 855 return YearMonth.of(year, month); 856 } 857 858 /** 859 * Returns a date formed from this year at the specified month-day. 860 * <p> 861 * This combines this year and the specified month-day to form a {@code LocalDate}. 862 * The month-day value of February 29th is only valid in a leap year. 863 * <p> 864 * This instance is immutable and unaffected by this method call. 865 * 866 * @param monthDay the month-day to use, not null 867 * @return the local date formed from this year and the specified month-day, not null 868 * @throws DateTimeException if the month-day is February 29th and this is not a leap year 869 */ 870 public LocalDate atMonthDay(MonthDay monthDay) { 871 return LocalDate.of(year, monthDay.getMonth(), monthDay.getDayOfMonth()); 872 } 873 874 //----------------------------------------------------------------------- 875 /** 876 * Compares this year to another year. 877 * <p> 878 * The comparison is based on the value of the year. 879 * It is "consistent with equals", as defined by {@link Comparable}. 880 * 881 * @param other the other year to compare to, not null 882 * @return the comparator value, negative if less, positive if greater 883 */ 884 public int compareTo(Year other) { 885 return year - other.year; 886 } 887 888 /** 889 * Is this year after the specified year. 890 * 891 * @param other the other year to compare to, not null 892 * @return true if this is after the specified year 893 */ 894 public boolean isAfter(Year other) { 895 return year > other.year; 896 } 897 898 /** 899 * Is this year before the specified year. 900 * 901 * @param other the other year to compare to, not null 902 * @return true if this point is before the specified year 903 */ 933 @Override 934 public int hashCode() { 935 return year; 936 } 937 938 //----------------------------------------------------------------------- 939 /** 940 * Outputs this year as a {@code String}. 941 * 942 * @return a string representation of this year, not null 943 */ 944 @Override 945 public String toString() { 946 return Integer.toString(year); 947 } 948 949 /** 950 * Outputs this year as a {@code String} using the formatter. 951 * <p> 952 * This year will be passed to the formatter 953 * {@link DateTimeFormatter#print(TemporalAccessor) print method}. 954 * 955 * @param formatter the formatter to use, not null 956 * @return the formatted year string, not null 957 * @throws DateTimeException if an error occurs during printing 958 */ 959 public String toString(DateTimeFormatter formatter) { 960 Objects.requireNonNull(formatter, "formatter"); 961 return formatter.print(this); 962 } 963 964 //----------------------------------------------------------------------- 965 /** 966 * Writes the object using a 967 * <a href="../../../serialized-form.html#java.time.temporal.Ser">dedicated serialized form</a>. 968 * <pre> 969 * out.writeByte(4); // identifies this as a Year 970 * out.writeInt(year); 971 * </pre> 972 * 973 * @return the instance of {@code Ser}, not null 974 */ 975 private Object writeReplace() { 976 return new Ser(Ser.YEAR_TYPE, this); 977 } 978 979 /** 980 * Defend against malicious streams. 981 * @return never 982 * @throws InvalidObjectException always 983 */ 984 private Object readResolve() throws ObjectStreamException { 985 throw new InvalidObjectException("Deserialization via serialization delegate"); 986 } 987 988 void writeExternal(DataOutput out) throws IOException { 989 out.writeInt(year); | 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.ERA; 65 import static java.time.temporal.ChronoField.YEAR; 66 import static java.time.temporal.ChronoField.YEAR_OF_ERA; 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.Chronology; 76 import java.time.chrono.IsoChronology; 77 import java.time.format.DateTimeFormatter; 78 import java.time.format.DateTimeFormatterBuilder; 79 import java.time.format.DateTimeParseException; 80 import java.time.format.SignStyle; 81 import java.time.temporal.ChronoField; 82 import java.time.temporal.ChronoUnit; 83 import java.time.temporal.Queries; 84 import java.time.temporal.Temporal; 85 import java.time.temporal.TemporalAccessor; 86 import java.time.temporal.TemporalAdjuster; 87 import java.time.temporal.TemporalAmount; 88 import java.time.temporal.TemporalField; 89 import java.time.temporal.TemporalQuery; 90 import java.time.temporal.TemporalUnit; 91 import java.time.temporal.ValueRange; 92 import java.util.Objects; 93 94 /** 95 * A year in the ISO-8601 calendar system, such as {@code 2007}. 96 * <p> 97 * {@code Year} is an immutable date-time object that represents a year. 98 * Any field that can be derived from a year can be obtained. 99 * <p> 100 * <b>Note that years in the ISO chronology only align with years in the 101 * Gregorian-Julian system for modern years. Parts of Russia did not switch to the 102 * modern Gregorian/ISO rules until 1920. 103 * As such, historical years must be treated with caution.</b> 104 * <p> 105 * This class does not store or represent a month, day, time or time-zone. 106 * For example, the value "2007" can be stored in a {@code Year}. 107 * <p> 108 * Years represented by this class follow the ISO-8601 standard and use 109 * the proleptic numbering system. Year 1 is preceded by year 0, then by year -1. 110 * <p> 111 * The ISO-8601 calendar system is the modern civil calendar system used today 202 * This method accepts a year value from the proleptic ISO calendar system. 203 * <p> 204 * The year 2AD/CE is represented by 2.<br> 205 * The year 1AD/CE is represented by 1.<br> 206 * The year 1BC/BCE is represented by 0.<br> 207 * The year 2BC/BCE is represented by -1.<br> 208 * 209 * @param isoYear the ISO proleptic year to represent, from {@code MIN_VALUE} to {@code MAX_VALUE} 210 * @return the year, not null 211 * @throws DateTimeException if the field is invalid 212 */ 213 public static Year of(int isoYear) { 214 YEAR.checkValidValue(isoYear); 215 return new Year(isoYear); 216 } 217 218 //----------------------------------------------------------------------- 219 /** 220 * Obtains an instance of {@code Year} from a temporal object. 221 * <p> 222 * This obtains a year based on the specified temporal. 223 * A {@code TemporalAccessor} represents an arbitrary set of date and time information, 224 * which this factory converts to an instance of {@code Year}. 225 * <p> 226 * The conversion extracts the {@link ChronoField#YEAR year} field. 227 * The extraction is only permitted if the temporal object has an ISO 228 * chronology, or can be converted to a {@code LocalDate}. 229 * <p> 230 * This method matches the signature of the functional interface {@link TemporalQuery} 231 * allowing it to be used in queries via method reference, {@code Year::from}. 232 * 233 * @param temporal the temporal object to convert, not null 234 * @return the year, not null 235 * @throws DateTimeException if unable to convert to a {@code Year} 236 */ 237 public static Year from(TemporalAccessor temporal) { 238 if (temporal instanceof Year) { 239 return (Year) temporal; 240 } 241 try { 242 if (IsoChronology.INSTANCE.equals(Chronology.from(temporal)) == false) { 243 temporal = LocalDate.from(temporal); 244 } 245 return of(temporal.get(YEAR)); 246 } catch (DateTimeException ex) { 247 throw new DateTimeException("Unable to obtain Year from TemporalAccessor: " + temporal.getClass(), ex); 248 } 249 } 250 251 //----------------------------------------------------------------------- 252 /** 253 * Obtains an instance of {@code Year} from a text string such as {@code 2007}. 254 * <p> 255 * The string must represent a valid year. 256 * Years outside the range 0000 to 9999 must be prefixed by the plus or minus symbol. 257 * 258 * @param text the text to parse such as "2007", not null 259 * @return the parsed year, not null 260 * @throws DateTimeParseException if the text cannot be parsed 261 */ 262 public static Year parse(CharSequence text) { 316 /** 317 * Gets the year value. 318 * <p> 319 * The year returned by this method is proleptic as per {@code get(YEAR)}. 320 * 321 * @return the year, {@code MIN_VALUE} to {@code MAX_VALUE} 322 */ 323 public int getValue() { 324 return year; 325 } 326 327 //----------------------------------------------------------------------- 328 /** 329 * Checks if the specified field is supported. 330 * <p> 331 * This checks if this year can be queried for the specified field. 332 * If false, then calling the {@link #range(TemporalField) range} and 333 * {@link #get(TemporalField) get} methods will throw an exception. 334 * <p> 335 * If the field is a {@link ChronoField} then the query is implemented here. 336 * The supported fields are: 337 * <ul> 338 * <li>{@code YEAR_OF_ERA} 339 * <li>{@code YEAR} 340 * <li>{@code ERA} 341 * </ul> 342 * All other {@code ChronoField} instances will return false. 343 * <p> 344 * If the field is not a {@code ChronoField}, then the result of this method 345 * is obtained by invoking {@code TemporalField.isSupportedBy(TemporalAccessor)} 346 * passing {@code this} as the argument. 347 * Whether the field is supported is determined by the field. 348 * 349 * @param field the field to check, null returns false 350 * @return true if the field is supported on this year, false if not 351 */ 352 @Override 353 public boolean isSupported(TemporalField field) { 354 if (field instanceof ChronoField) { 355 return field == YEAR || field == YEAR_OF_ERA || field == ERA; 356 } 357 return field != null && field.isSupportedBy(this); 358 } 359 360 /** 361 * Gets the range of valid values for the specified field. 362 * <p> 363 * The range object expresses the minimum and maximum valid values for a field. 364 * This year is used to enhance the accuracy of the returned range. 365 * If it is not possible to return the range, because the field is not supported 366 * or for some other reason, an exception is thrown. 367 * <p> 368 * If the field is a {@link ChronoField} then the query is implemented here. 369 * The {@link #isSupported(TemporalField) supported fields} will return 370 * appropriate range instances. 371 * All other {@code ChronoField} instances will throw a {@code DateTimeException}. 372 * <p> 373 * If the field is not a {@code ChronoField}, then the result of this method 374 * is obtained by invoking {@code TemporalField.rangeRefinedBy(TemporalAccessor)} 375 * passing {@code this} as the argument. 376 * Whether the range can be obtained is determined by the field. 377 * 378 * @param field the field to query the range for, not null 379 * @return the range of valid values for the field, not null 380 * @throws DateTimeException if the range for the field cannot be obtained 381 */ 382 @Override 383 public ValueRange range(TemporalField field) { 384 if (field == YEAR_OF_ERA) { 385 return (year <= 0 ? ValueRange.of(1, MAX_VALUE + 1) : ValueRange.of(1, MAX_VALUE)); 386 } 387 return Temporal.super.range(field); 388 } 389 390 /** 391 * Gets the value of the specified field from this year as an {@code int}. 392 * <p> 393 * This queries this year for the value for the specified field. 394 * The returned value will always be within the valid range of values for the field. 395 * If it is not possible to return the value, because the field is not supported 396 * or for some other reason, an exception is thrown. 397 * <p> 398 * If the field is a {@link ChronoField} then the query is implemented here. 399 * The {@link #isSupported(TemporalField) supported fields} will return valid 400 * values based on this year. 401 * All other {@code ChronoField} instances will throw a {@code DateTimeException}. 402 * <p> 403 * If the field is not a {@code ChronoField}, then the result of this method 404 * is obtained by invoking {@code TemporalField.getFrom(TemporalAccessor)} 405 * passing {@code this} as the argument. Whether the value can be obtained, 406 * and what the value represents, is determined by the field. 407 * 408 * @param field the field to get, not null 409 * @return the value for the field 410 * @throws DateTimeException if a value for the field cannot be obtained 411 * @throws ArithmeticException if numeric overflow occurs 412 */ 413 @Override // override for Javadoc 414 public int get(TemporalField field) { 415 return range(field).checkValidIntValue(getLong(field), field); 416 } 417 418 /** 419 * Gets the value of the specified field from this year as a {@code long}. 420 * <p> 421 * This queries this year for the value for the specified field. 422 * If it is not possible to return the value, because the field is not supported 423 * or for some other reason, an exception is thrown. 424 * <p> 425 * If the field is a {@link ChronoField} then the query is implemented here. 426 * The {@link #isSupported(TemporalField) supported fields} will return valid 427 * values based on this year. 428 * All other {@code ChronoField} instances will throw a {@code DateTimeException}. 429 * <p> 430 * If the field is not a {@code ChronoField}, then the result of this method 431 * is obtained by invoking {@code TemporalField.getFrom(TemporalAccessor)} 432 * passing {@code this} as the argument. Whether the value can be obtained, 433 * and what the value represents, is determined by the field. 434 * 435 * @param field the field to get, not null 436 * @return the value for the field 437 * @throws DateTimeException if a value for the field cannot be obtained 438 * @throws ArithmeticException if numeric overflow occurs 439 */ 440 @Override 441 public long getLong(TemporalField field) { 442 if (field instanceof ChronoField) { 443 switch ((ChronoField) field) { 444 case YEAR_OF_ERA: return (year < 1 ? 1 - year : year); 445 case YEAR: return year; 446 case ERA: return (year < 1 ? 0 : 1); 447 } 448 throw new DateTimeException("Unsupported field: " + field.getName()); 449 } 450 return field.getFrom(this); 451 } 452 453 //----------------------------------------------------------------------- 454 /** 455 * Checks if the year is a leap year, according to the ISO proleptic 456 * calendar system rules. 457 * <p> 458 * This method applies the current rules for leap years across the whole time-line. 459 * In general, a year is a leap year if it is divisible by four without 460 * remainder. However, years divisible by 100, are not leap years, with 461 * the exception of years divisible by 400 which are. 462 * <p> 463 * For example, 1904 is a leap year it is divisible by 4. 464 * 1900 was not a leap year as it is divisible by 100, however 2000 was a 465 * leap year as it is divisible by 400. 466 * <p> 467 * The calculation is proleptic - applying the same rules into the far future and far past. 468 * This is historically inaccurate, but is correct for the ISO-8601 standard. 469 * 470 * @return true if the year is leap, false otherwise 482 * @param monthDay the month-day to validate, null returns false 483 * @return true if the month and day are valid for this year 484 */ 485 public boolean isValidMonthDay(MonthDay monthDay) { 486 return monthDay != null && monthDay.isValidYear(year); 487 } 488 489 /** 490 * Gets the length of this year in days. 491 * 492 * @return the length of this year in days, 365 or 366 493 */ 494 public int length() { 495 return isLeap() ? 366 : 365; 496 } 497 498 //----------------------------------------------------------------------- 499 /** 500 * Returns an adjusted copy of this year. 501 * <p> 502 * This returns a {@code Year}, based on this one, with the year adjusted. 503 * The adjustment takes place using the specified adjuster strategy object. 504 * Read the documentation of the adjuster to understand what adjustment will be made. 505 * <p> 506 * The result of this method is obtained by invoking the 507 * {@link TemporalAdjuster#adjustInto(Temporal)} method on the 508 * specified adjuster passing {@code this} as the argument. 509 * <p> 510 * This instance is immutable and unaffected by this method call. 511 * 512 * @param adjuster the adjuster to use, not null 513 * @return a {@code Year} based on {@code this} with the adjustment made, not null 514 * @throws DateTimeException if the adjustment cannot be made 515 * @throws ArithmeticException if numeric overflow occurs 516 */ 517 @Override 518 public Year with(TemporalAdjuster adjuster) { 519 return (Year) adjuster.adjustInto(this); 520 } 521 522 /** 523 * Returns a copy of this year with the specified field set to a new value. 524 * <p> 525 * This returns a {@code Year}, based on this one, with the value 526 * for the specified field changed. 527 * If it is not possible to set the value, because the field is not supported or for 528 * some other reason, an exception is thrown. 529 * <p> 530 * If the field is a {@link ChronoField} then the adjustment is implemented here. 531 * The supported fields behave as follows: 532 * <ul> 533 * <li>{@code YEAR_OF_ERA} - 534 * Returns a {@code Year} with the specified year-of-era 535 * The era will be unchanged. 536 * <li>{@code YEAR} - 537 * Returns a {@code Year} with the specified year. 538 * This completely replaces the date and is equivalent to {@link #of(int)}. 539 * <li>{@code ERA} - 540 * Returns a {@code Year} with the specified era. 541 * The year-of-era will be unchanged. 542 * </ul> 543 * <p> 544 * In all cases, if the new value is outside the valid range of values for the field 545 * then a {@code DateTimeException} will be thrown. 546 * <p> 547 * All other {@code ChronoField} instances will throw a {@code DateTimeException}. 548 * <p> 549 * If the field is not a {@code ChronoField}, then the result of this method 550 * is obtained by invoking {@code TemporalField.adjustInto(Temporal, long)} 551 * passing {@code this} as the argument. In this case, the field determines 552 * whether and how to adjust the instant. 553 * <p> 554 * This instance is immutable and unaffected by this method call. 555 * 556 * @param field the field to set in the result, not null 557 * @param newValue the new value of the field in the result 558 * @return a {@code Year} based on {@code this} with the specified field set, not null 559 * @throws DateTimeException if the field cannot be set 560 * @throws ArithmeticException if numeric overflow occurs 561 */ 562 @Override 563 public Year with(TemporalField field, long newValue) { 564 if (field instanceof ChronoField) { 565 ChronoField f = (ChronoField) field; 566 f.checkValidValue(newValue); 567 switch (f) { 568 case YEAR_OF_ERA: return Year.of((int) (year < 1 ? 1 - newValue : newValue)); 569 case YEAR: return Year.of((int) newValue); 570 case ERA: return (getLong(ERA) == newValue ? this : Year.of(1 - year)); 571 } 572 throw new DateTimeException("Unsupported field: " + field.getName()); 573 } 574 return field.adjustInto(this, newValue); 575 } 576 577 //----------------------------------------------------------------------- 578 /** 579 * Returns a copy of this year with the specified amount added. 580 * <p> 581 * This returns a {@code Year}, based on this one, with the specified amount added. 582 * The amount is typically {@link Period} but may be any other type implementing 583 * the {@link TemporalAmount} interface. 584 * <p> 585 * The calculation is delegated to the amount object by calling 586 * {@link TemporalAmount#addTo(Temporal)}. The amount implementation is free 587 * to implement the addition in any way it wishes, however it typically 588 * calls back to {@link #plus(long, TemporalUnit)}. Consult the documentation 589 * of the amount implementation to determine if it can be successfully added. 590 * <p> 591 * This instance is immutable and unaffected by this method call. 592 * 593 * @param amountToAdd the amount to add, not null 594 * @return a {@code Year} based on this year with the addition made, not null 595 * @throws DateTimeException if the addition cannot be made 596 * @throws ArithmeticException if numeric overflow occurs 597 */ 598 @Override 599 public Year plus(TemporalAmount amountToAdd) { 600 return (Year) amountToAdd.addTo(this); 601 } 602 603 /** 604 * Returns a copy of this year with the specified amount added. 605 * <p> 606 * This returns a {@code Year}, based on this one, with the amount 607 * in terms of the unit added. If it is not possible to add the amount, because the 608 * unit is not supported or for some other reason, an exception is thrown. 609 * <p> 610 * If the field is a {@link ChronoUnit} then the addition is implemented here. 611 * The supported fields behave as follows: 612 * <ul> 613 * <li>{@code YEARS} - 614 * Returns a {@code Year} with the specified number of years added. 615 * This is equivalent to {@link #plusYears(long)}. 616 * <li>{@code DECADES} - 617 * Returns a {@code Year} with the specified number of decades added. 618 * This is equivalent to calling {@link #plusYears(long)} with the amount 619 * multiplied by 10. 620 * <li>{@code CENTURIES} - 621 * Returns a {@code Year} with the specified number of centuries added. 622 * This is equivalent to calling {@link #plusYears(long)} with the amount 623 * multiplied by 100. 624 * <li>{@code MILLENNIA} - 625 * Returns a {@code Year} with the specified number of millennia added. 626 * This is equivalent to calling {@link #plusYears(long)} with the amount 627 * multiplied by 1,000. 628 * <li>{@code ERAS} - 629 * Returns a {@code Year} with the specified number of eras added. 630 * Only two eras are supported so the amount must be one, zero or minus one. 631 * If the amount is non-zero then the year is changed such that the year-of-era 632 * is unchanged. 633 * </ul> 634 * <p> 635 * All other {@code ChronoUnit} instances will throw a {@code DateTimeException}. 636 * <p> 637 * If the field is not a {@code ChronoUnit}, then the result of this method 638 * is obtained by invoking {@code TemporalUnit.addTo(Temporal, long)} 639 * passing {@code this} as the argument. In this case, the unit determines 640 * whether and how to perform the addition. 641 * <p> 642 * This instance is immutable and unaffected by this method call. 643 * 644 * @param amountToAdd the amount of the unit to add to the result, may be negative 645 * @param unit the unit of the amount to add, not null 646 * @return a {@code Year} based on this year with the specified amount added, not null 647 * @throws DateTimeException if the addition cannot be made 648 * @throws ArithmeticException if numeric overflow occurs 649 */ 650 @Override 651 public Year plus(long amountToAdd, TemporalUnit unit) { 652 if (unit instanceof ChronoUnit) { 653 switch ((ChronoUnit) unit) { 654 case YEARS: return plusYears(amountToAdd); 655 case DECADES: return plusYears(Math.multiplyExact(amountToAdd, 10)); 656 case CENTURIES: return plusYears(Math.multiplyExact(amountToAdd, 100)); 657 case MILLENNIA: return plusYears(Math.multiplyExact(amountToAdd, 1000)); 658 case ERAS: return with(ERA, Math.addExact(getLong(ERA), amountToAdd)); 659 } 660 throw new DateTimeException("Unsupported unit: " + unit.getName()); 661 } 662 return unit.addTo(this, amountToAdd); 663 } 664 665 /** 666 * Returns a copy of this year with the specified number of years added. 667 * <p> 668 * This instance is immutable and unaffected by this method call. 669 * 670 * @param yearsToAdd the years to add, may be negative 671 * @return a {@code Year} based on this year with the period added, not null 672 * @throws DateTimeException if the result exceeds the supported year range 673 */ 674 public Year plusYears(long yearsToAdd) { 675 if (yearsToAdd == 0) { 676 return this; 677 } 678 return of(YEAR.checkValidIntValue(year + yearsToAdd)); // overflow safe 679 } 680 681 //----------------------------------------------------------------------- 682 /** 683 * Returns a copy of this year with the specified amount subtracted. 684 * <p> 685 * This returns a {@code Year}, based on this one, with the specified amount subtracted. 686 * The amount is typically {@link Period} but may be any other type implementing 687 * the {@link TemporalAmount} interface. 688 * <p> 689 * The calculation is delegated to the amount object by calling 690 * {@link TemporalAmount#subtractFrom(Temporal)}. The amount implementation is free 691 * to implement the subtraction in any way it wishes, however it typically 692 * calls back to {@link #minus(long, TemporalUnit)}. Consult the documentation 693 * of the amount implementation to determine if it can be successfully subtracted. 694 * <p> 695 * This instance is immutable and unaffected by this method call. 696 * 697 * @param amountToSubtract the amount to subtract, not null 698 * @return a {@code Year} based on this year with the subtraction made, not null 699 * @throws DateTimeException if the subtraction cannot be made 700 * @throws ArithmeticException if numeric overflow occurs 701 */ 702 @Override 703 public Year minus(TemporalAmount amountToSubtract) { 704 return (Year) amountToSubtract.subtractFrom(this); 705 } 706 707 /** 708 * Returns a copy of this year-month with the specified amount subtracted. 709 * <p> 710 * This returns a {@code YearMonth}, based on this one, with the amount 711 * in terms of the unit subtracted. If it is not possible to subtract the amount, 712 * because the unit is not supported or for some other reason, an exception is thrown. 713 * <p> 714 * This method is equivalent to {@link #plus(long, TemporalUnit)} with the amount negated. 715 * See that method for a full description of how addition, and thus subtraction, works. 716 * <p> 717 * This instance is immutable and unaffected by this method call. 718 * 719 * @param amountToSubtract the amount of the unit to subtract from the result, may be negative 720 * @param unit the unit of the amount to subtract, not null 721 * @return a {@code YearMonth} based on this year-month with the specified amount subtracted, not null 722 * @throws DateTimeException if the subtraction cannot be made 723 * @throws ArithmeticException if numeric overflow occurs 724 */ 725 @Override 726 public Year minus(long amountToSubtract, TemporalUnit unit) { 727 return (amountToSubtract == Long.MIN_VALUE ? plus(Long.MAX_VALUE, unit).plus(1, unit) : plus(-amountToSubtract, unit)); 728 } 729 730 /** 731 * Returns a copy of this year with the specified number of years subtracted. 732 * <p> 733 * This instance is immutable and unaffected by this method call. 734 * 735 * @param yearsToSubtract the years to subtract, may be negative 736 * @return a {@code Year} based on this year with the period subtracted, not null 737 * @throws DateTimeException if the result exceeds the supported year range 738 */ 739 public Year minusYears(long yearsToSubtract) { 740 return (yearsToSubtract == Long.MIN_VALUE ? plusYears(Long.MAX_VALUE).plusYears(1) : plusYears(-yearsToSubtract)); 741 } 742 743 //----------------------------------------------------------------------- 745 * Queries this year using the specified query. 746 * <p> 747 * This queries this year using the specified query strategy object. 748 * The {@code TemporalQuery} object defines the logic to be used to 749 * obtain the result. Read the documentation of the query to understand 750 * what the result of this method will be. 751 * <p> 752 * The result of this method is obtained by invoking the 753 * {@link TemporalQuery#queryFrom(TemporalAccessor)} method on the 754 * specified query passing {@code this} as the argument. 755 * 756 * @param <R> the type of the result 757 * @param query the query to invoke, not null 758 * @return the query result, null may be returned (defined by the query) 759 * @throws DateTimeException if unable to query (defined by the query) 760 * @throws ArithmeticException if numeric overflow occurs (defined by the query) 761 */ 762 @SuppressWarnings("unchecked") 763 @Override 764 public <R> R query(TemporalQuery<R> query) { 765 if (query == Queries.chronology()) { 766 return (R) IsoChronology.INSTANCE; 767 } else if (query == Queries.precision()) { 768 return (R) YEARS; 769 } 770 return Temporal.super.query(query); 771 } 772 773 /** 774 * Adjusts the specified temporal object to have this year. 775 * <p> 776 * This returns a temporal object of the same observable type as the input 777 * with the year changed to be the same as this. 778 * <p> 779 * The adjustment is equivalent to using {@link Temporal#with(TemporalField, long)} 780 * passing {@link ChronoField#YEAR} as the field. 781 * If the specified temporal object does not use the ISO calendar system then 782 * a {@code DateTimeException} is thrown. 783 * <p> 784 * In most cases, it is clearer to reverse the calling pattern by using 785 * {@link Temporal#with(TemporalAdjuster)}: 786 * <pre> 787 * // these two lines are equivalent, but the second approach is recommended 788 * temporal = thisYear.adjustInto(temporal); 789 * temporal = temporal.with(thisYear); 790 * </pre> 791 * <p> 792 * This instance is immutable and unaffected by this method call. 793 * 794 * @param temporal the target object to be adjusted, not null 795 * @return the adjusted object, not null 796 * @throws DateTimeException if unable to make the adjustment 797 * @throws ArithmeticException if numeric overflow occurs 798 */ 799 @Override 800 public Temporal adjustInto(Temporal temporal) { 801 if (Chronology.from(temporal).equals(IsoChronology.INSTANCE) == false) { 802 throw new DateTimeException("Adjustment only supported on ISO date-time"); 803 } 804 return temporal.with(YEAR, year); 805 } 806 807 /** 808 * Calculates the period between this year and another year in 809 * terms of the specified unit. 810 * <p> 811 * This calculates the period between two years in terms of a single unit. 812 * The start and end points are {@code this} and the specified year. 813 * The result will be negative if the end is before the start. 814 * The {@code Temporal} passed to this method must be a {@code Year}. 815 * For example, the period in decades between two year can be calculated 816 * using {@code startYear.periodUntil(endYear, DECADES)}. 817 * <p> 818 * The calculation returns a whole number, representing the number of 819 * complete units between the two years. 820 * For example, the period in decades between 2012 and 2031 821 * will only be one decade as it is one year short of two decades. 822 * <p> 823 * There are two equivalent ways of using this method. 824 * The first is to invoke this method. 825 * The second is to use {@link TemporalUnit#between(Temporal, Temporal)}: 826 * <pre> 827 * // these two lines are equivalent 828 * amount = start.periodUntil(end, YEARS); 829 * amount = YEARS.between(start, end); 830 * </pre> 831 * The choice should be made based on which makes the code more readable. 832 * <p> 833 * The calculation is implemented in this method for {@link ChronoUnit}. 834 * The units {@code YEARS}, {@code DECADES}, {@code CENTURIES}, 835 * {@code MILLENNIA} and {@code ERAS} are supported. 836 * Other {@code ChronoUnit} values will throw an exception. 837 * <p> 838 * If the unit is not a {@code ChronoUnit}, then the result of this method 839 * is obtained by invoking {@code TemporalUnit.between(Temporal, Temporal)} 840 * passing {@code this} as the first argument and the input temporal as 841 * the second argument. 842 * <p> 843 * This instance is immutable and unaffected by this method call. 844 * 845 * @param endYear the end year, which must be a {@code Year}, not null 846 * @param unit the unit to measure the period in, not null 847 * @return the amount of the period between this year and the end year 848 * @throws DateTimeException if the period cannot be calculated 849 * @throws ArithmeticException if numeric overflow occurs 850 */ 851 @Override 852 public long periodUntil(Temporal endYear, TemporalUnit unit) { 853 if (endYear instanceof Year == false) { 854 Objects.requireNonNull(endYear, "endYear"); 855 throw new DateTimeException("Unable to calculate period between objects of two different types"); 856 } 857 Year end = (Year) endYear; 858 if (unit instanceof ChronoUnit) { 859 long yearsUntil = ((long) end.year) - year; // no overflow 860 switch ((ChronoUnit) unit) { 861 case YEARS: return yearsUntil; 862 case DECADES: return yearsUntil / 10; 863 case CENTURIES: return yearsUntil / 100; 864 case MILLENNIA: return yearsUntil / 1000; 865 case ERAS: return end.getLong(ERA) - getLong(ERA); 866 } 867 throw new DateTimeException("Unsupported unit: " + unit.getName()); 868 } 869 return unit.between(this, endYear); 870 } 871 872 //----------------------------------------------------------------------- 873 /** 874 * Combines this year with a day-of-year to create a {@code LocalDate}. 875 * <p> 876 * This returns a {@code LocalDate} formed from this year and the specified day-of-year. 877 * <p> 878 * The day-of-year value 366 is only valid in a leap year. 879 * 880 * @param dayOfYear the day-of-year to use, not null 881 * @return the local date formed from this year and the specified date of year, not null 882 * @throws DateTimeException if the day of year is zero or less, 366 or greater or equal 883 * to 366 and this is not a leap year 884 */ 885 public LocalDate atDay(int dayOfYear) { 886 return LocalDate.ofYearDay(year, dayOfYear); 887 } 888 889 /** 890 * Combines this year with a month to create a {@code YearMonth}. 891 * <p> 892 * This returns a {@code YearMonth} formed from this year and the specified month. 893 * All possible combinations of year and month are valid. 894 * <p> 895 * This method can be used as part of a chain to produce a date: 896 * <pre> 897 * LocalDate date = year.atMonth(month).atDay(day); 898 * </pre> 899 * 900 * @param month the month-of-year to use, not null 901 * @return the year-month formed from this year and the specified month, not null 902 */ 903 public YearMonth atMonth(Month month) { 904 return YearMonth.of(year, month); 905 } 906 907 /** 908 * Combines this year with a month to create a {@code YearMonth}. 909 * <p> 910 * This returns a {@code YearMonth} formed from this year and the specified month. 911 * All possible combinations of year and month are valid. 912 * <p> 913 * This method can be used as part of a chain to produce a date: 914 * <pre> 915 * LocalDate date = year.atMonth(month).atDay(day); 916 * </pre> 917 * 918 * @param month the month-of-year to use, from 1 (January) to 12 (December) 919 * @return the year-month formed from this year and the specified month, not null 920 * @throws DateTimeException if the month is invalid 921 */ 922 public YearMonth atMonth(int month) { 923 return YearMonth.of(year, month); 924 } 925 926 /** 927 * Combines this year with a month-day to create a {@code LocalDate}. 928 * <p> 929 * This returns a {@code LocalDate} formed from this year and the specified month-day. 930 * <p> 931 * A month-day of February 29th will be adjusted to February 28th in the resulting 932 * date if the year is not a leap year. 933 * 934 * @param monthDay the month-day to use, not null 935 * @return the local date formed from this year and the specified month-day, not null 936 */ 937 public LocalDate atMonthDay(MonthDay monthDay) { 938 return monthDay.atYear(year); 939 } 940 941 //----------------------------------------------------------------------- 942 /** 943 * Compares this year to another year. 944 * <p> 945 * The comparison is based on the value of the year. 946 * It is "consistent with equals", as defined by {@link Comparable}. 947 * 948 * @param other the other year to compare to, not null 949 * @return the comparator value, negative if less, positive if greater 950 */ 951 @Override 952 public int compareTo(Year other) { 953 return year - other.year; 954 } 955 956 /** 957 * Is this year after the specified year. 958 * 959 * @param other the other year to compare to, not null 960 * @return true if this is after the specified year 961 */ 962 public boolean isAfter(Year other) { 963 return year > other.year; 964 } 965 966 /** 967 * Is this year before the specified year. 968 * 969 * @param other the other year to compare to, not null 970 * @return true if this point is before the specified year 971 */ 1001 @Override 1002 public int hashCode() { 1003 return year; 1004 } 1005 1006 //----------------------------------------------------------------------- 1007 /** 1008 * Outputs this year as a {@code String}. 1009 * 1010 * @return a string representation of this year, not null 1011 */ 1012 @Override 1013 public String toString() { 1014 return Integer.toString(year); 1015 } 1016 1017 /** 1018 * Outputs this year as a {@code String} using the formatter. 1019 * <p> 1020 * This year will be passed to the formatter 1021 * {@link DateTimeFormatter#format(TemporalAccessor) format method}. 1022 * 1023 * @param formatter the formatter to use, not null 1024 * @return the formatted year string, not null 1025 * @throws DateTimeException if an error occurs during printing 1026 */ 1027 public String toString(DateTimeFormatter formatter) { 1028 Objects.requireNonNull(formatter, "formatter"); 1029 return formatter.format(this); 1030 } 1031 1032 //----------------------------------------------------------------------- 1033 /** 1034 * Writes the object using a 1035 * <a href="../../../serialized-form.html#java.time.temporal.Ser">dedicated serialized form</a>. 1036 * <pre> 1037 * out.writeByte(11); // identifies this as a Year 1038 * out.writeInt(year); 1039 * </pre> 1040 * 1041 * @return the instance of {@code Ser}, not null 1042 */ 1043 private Object writeReplace() { 1044 return new Ser(Ser.YEAR_TYPE, this); 1045 } 1046 1047 /** 1048 * Defend against malicious streams. 1049 * @return never 1050 * @throws InvalidObjectException always 1051 */ 1052 private Object readResolve() throws ObjectStreamException { 1053 throw new InvalidObjectException("Deserialization via serialization delegate"); 1054 } 1055 1056 void writeExternal(DataOutput out) throws IOException { 1057 out.writeInt(year); |