1 /*
   2  * Copyright (c) 2012, 2023, 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) 2007-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.LocalTime.SECONDS_PER_DAY;
  65 import static java.time.temporal.ChronoField.ALIGNED_DAY_OF_WEEK_IN_MONTH;
  66 import static java.time.temporal.ChronoField.ALIGNED_DAY_OF_WEEK_IN_YEAR;
  67 import static java.time.temporal.ChronoField.ALIGNED_WEEK_OF_MONTH;
  68 import static java.time.temporal.ChronoField.ALIGNED_WEEK_OF_YEAR;
  69 import static java.time.temporal.ChronoField.DAY_OF_MONTH;
  70 import static java.time.temporal.ChronoField.DAY_OF_YEAR;
  71 import static java.time.temporal.ChronoField.EPOCH_DAY;
  72 import static java.time.temporal.ChronoField.ERA;
  73 import static java.time.temporal.ChronoField.MONTH_OF_YEAR;
  74 import static java.time.temporal.ChronoField.PROLEPTIC_MONTH;
  75 import static java.time.temporal.ChronoField.YEAR;
  76 
  77 import java.io.DataInput;
  78 import java.io.DataOutput;
  79 import java.io.IOException;
  80 import java.io.InvalidObjectException;
  81 import java.io.ObjectInputStream;
  82 import java.io.Serializable;
  83 import java.time.chrono.ChronoLocalDate;
  84 import java.time.chrono.IsoEra;
  85 import java.time.chrono.IsoChronology;
  86 import java.time.format.DateTimeFormatter;
  87 import java.time.format.DateTimeParseException;
  88 import java.time.temporal.ChronoField;
  89 import java.time.temporal.ChronoUnit;
  90 import java.time.temporal.Temporal;
  91 import java.time.temporal.TemporalAccessor;
  92 import java.time.temporal.TemporalAdjuster;
  93 import java.time.temporal.TemporalAmount;
  94 import java.time.temporal.TemporalField;
  95 import java.time.temporal.TemporalQueries;
  96 import java.time.temporal.TemporalQuery;
  97 import java.time.temporal.TemporalUnit;
  98 import java.time.temporal.UnsupportedTemporalTypeException;
  99 import java.time.temporal.ValueRange;
 100 import java.time.zone.ZoneOffsetTransition;
 101 import java.time.zone.ZoneRules;
 102 import java.util.Objects;
 103 import java.util.stream.LongStream;
 104 import java.util.stream.Stream;
 105 
 106 /**
 107  * A date without a time-zone in the ISO-8601 calendar system,
 108  * such as {@code 2007-12-03}.
 109  * <p>
 110  * {@code LocalDate} is an immutable date-time object that represents a date,
 111  * often viewed as year-month-day. Other date fields, such as day-of-year,
 112  * day-of-week and week-of-year, can also be accessed.
 113  * For example, the value "2nd October 2007" can be stored in a {@code LocalDate}.
 114  * <p>
 115  * This class does not store or represent a time or time-zone.
 116  * Instead, it is a description of the date, as used for birthdays.
 117  * It cannot represent an instant on the time-line without additional information
 118  * such as an offset or time-zone.
 119  * <p>
 120  * The ISO-8601 calendar system is the modern civil calendar system used today
 121  * in most of the world. It is equivalent to the proleptic Gregorian calendar
 122  * system, in which today's rules for leap years are applied for all time.
 123  * For most applications written today, the ISO-8601 rules are entirely suitable.
 124  * However, any application that makes use of historical dates, and requires them
 125  * to be accurate will find the ISO-8601 approach unsuitable.
 126  * <p>
 127  * This is a <a href="{@docRoot}/java.base/java/lang/doc-files/ValueBased.html">value-based</a>
 128  * class; programmers should treat instances that are
 129  * {@linkplain #equals(Object) equal} as interchangeable and should not
 130  * use instances for synchronization, or unpredictable behavior may
 131  * occur. For example, in a future release, synchronization may fail.
 132  * The {@code equals} method should be used for comparisons.
 133  *
 134  * @implSpec
 135  * This class is immutable and thread-safe.
 136  *
 137  * @since 1.8
 138  */
 139 @jdk.internal.ValueBased
 140 @jdk.internal.MigratedValueClass
 141 public final class LocalDate
 142         implements Temporal, TemporalAdjuster, ChronoLocalDate, Serializable {
 143 
 144     /**
 145      * The minimum supported {@code LocalDate}, '-999999999-01-01'.
 146      * This could be used by an application as a "far past" date.
 147      */
 148     public static final LocalDate MIN = LocalDate.of(Year.MIN_VALUE, 1, 1);
 149     /**
 150      * The maximum supported {@code LocalDate}, '+999999999-12-31'.
 151      * This could be used by an application as a "far future" date.
 152      */
 153     public static final LocalDate MAX = LocalDate.of(Year.MAX_VALUE, 12, 31);
 154     /**
 155      * The epoch year {@code LocalDate}, '1970-01-01'.
 156      *
 157      * @since 9
 158      */
 159     public static final LocalDate EPOCH = LocalDate.of(1970, 1, 1);
 160 
 161     /**
 162      * Serialization version.
 163      */
 164     @java.io.Serial
 165     private static final long serialVersionUID = 2942565459149668126L;
 166     /**
 167      * The number of days in a 400 year cycle.
 168      */
 169     private static final int DAYS_PER_CYCLE = 146097;
 170     /**
 171      * The number of days from year zero to year 1970.
 172      * There are five 400 year cycles from year zero to 2000.
 173      * There are 7 leap years from 1970 to 2000.
 174      */
 175     static final long DAYS_0000_TO_1970 = (DAYS_PER_CYCLE * 5L) - (30L * 365L + 7L);
 176 
 177     /**
 178      * The year.
 179      */
 180     private final int year;
 181     /**
 182      * The month-of-year.
 183      */
 184     private final short month;
 185     /**
 186      * The day-of-month.
 187      */
 188     private final short day;
 189 
 190     //-----------------------------------------------------------------------
 191     /**
 192      * Obtains the current date from the system clock in the default time-zone.
 193      * <p>
 194      * This will query the {@link Clock#systemDefaultZone() system clock} in the default
 195      * time-zone to obtain the current date.
 196      * <p>
 197      * Using this method will prevent the ability to use an alternate clock for testing
 198      * because the clock is hard-coded.
 199      *
 200      * @return the current date using the system clock and default time-zone, not null
 201      */
 202     public static LocalDate now() {
 203         return now(Clock.systemDefaultZone());
 204     }
 205 
 206     /**
 207      * Obtains the current date from the system clock in the specified time-zone.
 208      * <p>
 209      * This will query the {@link Clock#system(ZoneId) system clock} to obtain the current date.
 210      * Specifying the time-zone avoids dependence on the default time-zone.
 211      * <p>
 212      * Using this method will prevent the ability to use an alternate clock for testing
 213      * because the clock is hard-coded.
 214      *
 215      * @param zone  the zone ID to use, not null
 216      * @return the current date using the system clock, not null
 217      */
 218     public static LocalDate now(ZoneId zone) {
 219         return now(Clock.system(zone));
 220     }
 221 
 222     /**
 223      * Obtains the current date from the specified clock.
 224      * <p>
 225      * This will query the specified clock to obtain the current date - today.
 226      * Using this method allows the use of an alternate clock for testing.
 227      * The alternate clock may be introduced using {@link Clock dependency injection}.
 228      *
 229      * @param clock  the clock to use, not null
 230      * @return the current date, not null
 231      */
 232     public static LocalDate now(Clock clock) {
 233         Objects.requireNonNull(clock, "clock");
 234         final Instant now = clock.instant();  // called once
 235         return ofInstant(now, clock.getZone());
 236     }
 237 
 238     //-----------------------------------------------------------------------
 239     /**
 240      * Obtains an instance of {@code LocalDate} from a year, month and day.
 241      * <p>
 242      * This returns a {@code LocalDate} with the specified year, month and day-of-month.
 243      * The day must be valid for the year and month, otherwise an exception will be thrown.
 244      *
 245      * @param year  the year to represent, from MIN_YEAR to MAX_YEAR
 246      * @param month  the month-of-year to represent, not null
 247      * @param dayOfMonth  the day-of-month to represent, from 1 to 31
 248      * @return the local date, not null
 249      * @throws DateTimeException if the value of any field is out of range,
 250      *  or if the day-of-month is invalid for the month-year
 251      */
 252     public static LocalDate of(int year, Month month, int dayOfMonth) {
 253         YEAR.checkValidValue(year);
 254         Objects.requireNonNull(month, "month");
 255         DAY_OF_MONTH.checkValidValue(dayOfMonth);
 256         return create(year, month.getValue(), dayOfMonth);
 257     }
 258 
 259     /**
 260      * Obtains an instance of {@code LocalDate} from a year, month and day.
 261      * <p>
 262      * This returns a {@code LocalDate} with the specified year, month and day-of-month.
 263      * The day must be valid for the year and month, otherwise an exception will be thrown.
 264      *
 265      * @param year  the year to represent, from MIN_YEAR to MAX_YEAR
 266      * @param month  the month-of-year to represent, from 1 (January) to 12 (December)
 267      * @param dayOfMonth  the day-of-month to represent, from 1 to 31
 268      * @return the local date, not null
 269      * @throws DateTimeException if the value of any field is out of range,
 270      *  or if the day-of-month is invalid for the month-year
 271      */
 272     public static LocalDate of(int year, int month, int dayOfMonth) {
 273         YEAR.checkValidValue(year);
 274         MONTH_OF_YEAR.checkValidValue(month);
 275         DAY_OF_MONTH.checkValidValue(dayOfMonth);
 276         return create(year, month, dayOfMonth);
 277     }
 278 
 279     //-----------------------------------------------------------------------
 280     /**
 281      * Obtains an instance of {@code LocalDate} from a year and day-of-year.
 282      * <p>
 283      * This returns a {@code LocalDate} with the specified year and day-of-year.
 284      * The day-of-year must be valid for the year, otherwise an exception will be thrown.
 285      *
 286      * @param year  the year to represent, from MIN_YEAR to MAX_YEAR
 287      * @param dayOfYear  the day-of-year to represent, from 1 to 366
 288      * @return the local date, not null
 289      * @throws DateTimeException if the value of any field is out of range,
 290      *  or if the day-of-year is invalid for the year
 291      */
 292     public static LocalDate ofYearDay(int year, int dayOfYear) {
 293         YEAR.checkValidValue(year);
 294         DAY_OF_YEAR.checkValidValue(dayOfYear);
 295         boolean leap = IsoChronology.INSTANCE.isLeapYear(year);
 296         if (dayOfYear == 366 && leap == false) {
 297             throw new DateTimeException("Invalid date 'DayOfYear 366' as '" + year + "' is not a leap year");
 298         }
 299         Month moy = Month.of((dayOfYear - 1) / 31 + 1);
 300         int monthEnd = moy.firstDayOfYear(leap) + moy.length(leap) - 1;
 301         if (dayOfYear > monthEnd) {
 302             moy = moy.plus(1);
 303         }
 304         int dom = dayOfYear - moy.firstDayOfYear(leap) + 1;
 305         return new LocalDate(year, moy.getValue(), dom);
 306     }
 307 
 308     //-----------------------------------------------------------------------
 309     /**
 310      * Obtains an instance of {@code LocalDate} from an {@code Instant} and zone ID.
 311      * <p>
 312      * This creates a local date based on the specified instant.
 313      * First, the offset from UTC/Greenwich is obtained using the zone ID and instant,
 314      * which is simple as there is only one valid offset for each instant.
 315      * Then, the instant and offset are used to calculate the local date.
 316      *
 317      * @param instant  the instant to create the date from, not null
 318      * @param zone  the time-zone, which may be an offset, not null
 319      * @return the local date, not null
 320      * @throws DateTimeException if the result exceeds the supported range
 321      * @since 9
 322      */
 323     public static LocalDate ofInstant(Instant instant, ZoneId zone) {
 324         Objects.requireNonNull(instant, "instant");
 325         Objects.requireNonNull(zone, "zone");
 326         ZoneRules rules = zone.getRules();
 327         ZoneOffset offset = rules.getOffset(instant);
 328         long localSecond = instant.getEpochSecond() + offset.getTotalSeconds();
 329         long localEpochDay = Math.floorDiv(localSecond, SECONDS_PER_DAY);
 330         return ofEpochDay(localEpochDay);
 331     }
 332 
 333     //-----------------------------------------------------------------------
 334     /**
 335      * Obtains an instance of {@code LocalDate} from the epoch day count.
 336      * <p>
 337      * This returns a {@code LocalDate} with the specified epoch-day.
 338      * The {@link ChronoField#EPOCH_DAY EPOCH_DAY} is a simple incrementing count
 339      * of days where day 0 is 1970-01-01. Negative numbers represent earlier days.
 340      *
 341      * @param epochDay  the Epoch Day to convert, based on the epoch 1970-01-01
 342      * @return the local date, not null
 343      * @throws DateTimeException if the epoch day exceeds the supported date range
 344      */
 345     public static LocalDate ofEpochDay(long epochDay) {
 346         EPOCH_DAY.checkValidValue(epochDay);
 347         long zeroDay = epochDay + DAYS_0000_TO_1970;
 348         // find the march-based year
 349         zeroDay -= 60;  // adjust to 0000-03-01 so leap day is at end of four year cycle
 350         long adjust = 0;
 351         if (zeroDay < 0) {
 352             // adjust negative years to positive for calculation
 353             long adjustCycles = (zeroDay + 1) / DAYS_PER_CYCLE - 1;
 354             adjust = adjustCycles * 400;
 355             zeroDay += -adjustCycles * DAYS_PER_CYCLE;
 356         }
 357         long yearEst = (400 * zeroDay + 591) / DAYS_PER_CYCLE;
 358         long doyEst = zeroDay - (365 * yearEst + yearEst / 4 - yearEst / 100 + yearEst / 400);
 359         if (doyEst < 0) {
 360             // fix estimate
 361             yearEst--;
 362             doyEst = zeroDay - (365 * yearEst + yearEst / 4 - yearEst / 100 + yearEst / 400);
 363         }
 364         yearEst += adjust;  // reset any negative year
 365         int marchDoy0 = (int) doyEst;
 366 
 367         // convert march-based values back to january-based
 368         int marchMonth0 = (marchDoy0 * 5 + 2) / 153;
 369         int month = marchMonth0 + 3;
 370         if (month > 12) {
 371             month -= 12;
 372         }
 373         int dom = marchDoy0 - (marchMonth0 * 306 + 5) / 10 + 1;
 374         if (marchDoy0 >= 306) {
 375             yearEst++;
 376         }
 377 
 378         return new LocalDate((int)yearEst, month, dom);
 379     }
 380 
 381     //-----------------------------------------------------------------------
 382     /**
 383      * Obtains an instance of {@code LocalDate} from a temporal object.
 384      * <p>
 385      * This obtains a local date based on the specified temporal.
 386      * A {@code TemporalAccessor} represents an arbitrary set of date and time information,
 387      * which this factory converts to an instance of {@code LocalDate}.
 388      * <p>
 389      * The conversion uses the {@link TemporalQueries#localDate()} query, which relies
 390      * on extracting the {@link ChronoField#EPOCH_DAY EPOCH_DAY} field.
 391      * <p>
 392      * This method matches the signature of the functional interface {@link TemporalQuery}
 393      * allowing it to be used as a query via method reference, {@code LocalDate::from}.
 394      *
 395      * @param temporal  the temporal object to convert, not null
 396      * @return the local date, not null
 397      * @throws DateTimeException if unable to convert to a {@code LocalDate}
 398      */
 399     public static LocalDate from(TemporalAccessor temporal) {
 400         Objects.requireNonNull(temporal, "temporal");
 401         LocalDate date = temporal.query(TemporalQueries.localDate());
 402         if (date == null) {
 403             throw new DateTimeException("Unable to obtain LocalDate from TemporalAccessor: " +
 404                     temporal + " of type " + temporal.getClass().getName());
 405         }
 406         return date;
 407     }
 408 
 409     //-----------------------------------------------------------------------
 410     /**
 411      * Obtains an instance of {@code LocalDate} from a text string such as {@code 2007-12-03}.
 412      * <p>
 413      * The string must represent a valid date and is parsed using
 414      * {@link java.time.format.DateTimeFormatter#ISO_LOCAL_DATE}.
 415      *
 416      * @param text  the text to parse such as "2007-12-03", not null
 417      * @return the parsed local date, not null
 418      * @throws DateTimeParseException if the text cannot be parsed
 419      */
 420     public static LocalDate parse(CharSequence text) {
 421         return parse(text, DateTimeFormatter.ISO_LOCAL_DATE);
 422     }
 423 
 424     /**
 425      * Obtains an instance of {@code LocalDate} from a text string using a specific formatter.
 426      * <p>
 427      * The text is parsed using the formatter, returning a date.
 428      *
 429      * @param text  the text to parse, not null
 430      * @param formatter  the formatter to use, not null
 431      * @return the parsed local date, not null
 432      * @throws DateTimeParseException if the text cannot be parsed
 433      */
 434     public static LocalDate parse(CharSequence text, DateTimeFormatter formatter) {
 435         Objects.requireNonNull(formatter, "formatter");
 436         return formatter.parse(text, LocalDate::from);
 437     }
 438 
 439     //-----------------------------------------------------------------------
 440     /**
 441      * Creates a local date from the year, month and day fields.
 442      *
 443      * @param year  the year to represent, validated from MIN_YEAR to MAX_YEAR
 444      * @param month  the month-of-year to represent, from 1 to 12, validated
 445      * @param dayOfMonth  the day-of-month to represent, validated from 1 to 31
 446      * @return the local date, not null
 447      * @throws DateTimeException if the day-of-month is invalid for the month-year
 448      */
 449     private static LocalDate create(int year, int month, int dayOfMonth) {
 450         if (dayOfMonth > 28) {
 451             int dom = switch (month) {
 452                 case 2 -> (IsoChronology.INSTANCE.isLeapYear(year) ? 29 : 28);
 453                 case 4, 6, 9, 11 -> 30;
 454                 default -> 31;
 455             };
 456             if (dayOfMonth > dom) {
 457                 if (dayOfMonth == 29) {
 458                     throw new DateTimeException("Invalid date 'February 29' as '" + year + "' is not a leap year");
 459                 } else {
 460                     throw new DateTimeException("Invalid date '" + Month.of(month).name() + " " + dayOfMonth + "'");
 461                 }
 462             }
 463         }
 464         return new LocalDate(year, month, dayOfMonth);
 465     }
 466 
 467     /**
 468      * Resolves the date, resolving days past the end of month.
 469      *
 470      * @param year  the year to represent, validated from MIN_YEAR to MAX_YEAR
 471      * @param month  the month-of-year to represent, validated from 1 to 12
 472      * @param day  the day-of-month to represent, validated from 1 to 31
 473      * @return the resolved date, not null
 474      */
 475     private static LocalDate resolvePreviousValid(int year, int month, int day) {
 476         switch (month) {
 477             case 2 -> day = Math.min(day, IsoChronology.INSTANCE.isLeapYear(year) ? 29 : 28);
 478             case 4, 6, 9, 11 -> day = Math.min(day, 30);
 479         }
 480         return new LocalDate(year, month, day);
 481     }
 482 
 483     /**
 484      * Constructor, previously validated.
 485      *
 486      * @param year  the year to represent, from MIN_YEAR to MAX_YEAR
 487      * @param month  the month-of-year to represent, not null
 488      * @param dayOfMonth  the day-of-month to represent, valid for year-month, from 1 to 31
 489      */
 490     private LocalDate(int year, int month, int dayOfMonth) {
 491         this.year = year;
 492         this.month = (short) month;
 493         this.day = (short) dayOfMonth;
 494     }
 495 
 496     //-----------------------------------------------------------------------
 497     /**
 498      * Checks if the specified field is supported.
 499      * <p>
 500      * This checks if this date can be queried for the specified field.
 501      * If false, then calling the {@link #range(TemporalField) range},
 502      * {@link #get(TemporalField) get} and {@link #with(TemporalField, long)}
 503      * methods will throw an exception.
 504      * <p>
 505      * If the field is a {@link ChronoField} then the query is implemented here.
 506      * The supported fields are:
 507      * <ul>
 508      * <li>{@code DAY_OF_WEEK}
 509      * <li>{@code ALIGNED_DAY_OF_WEEK_IN_MONTH}
 510      * <li>{@code ALIGNED_DAY_OF_WEEK_IN_YEAR}
 511      * <li>{@code DAY_OF_MONTH}
 512      * <li>{@code DAY_OF_YEAR}
 513      * <li>{@code EPOCH_DAY}
 514      * <li>{@code ALIGNED_WEEK_OF_MONTH}
 515      * <li>{@code ALIGNED_WEEK_OF_YEAR}
 516      * <li>{@code MONTH_OF_YEAR}
 517      * <li>{@code PROLEPTIC_MONTH}
 518      * <li>{@code YEAR_OF_ERA}
 519      * <li>{@code YEAR}
 520      * <li>{@code ERA}
 521      * </ul>
 522      * All other {@code ChronoField} instances will return false.
 523      * <p>
 524      * If the field is not a {@code ChronoField}, then the result of this method
 525      * is obtained by invoking {@code TemporalField.isSupportedBy(TemporalAccessor)}
 526      * passing {@code this} as the argument.
 527      * Whether the field is supported is determined by the field.
 528      *
 529      * @param field  the field to check, null returns false
 530      * @return true if the field is supported on this date, false if not
 531      */
 532     @Override  // override for Javadoc
 533     public boolean isSupported(TemporalField field) {
 534         return ChronoLocalDate.super.isSupported(field);
 535     }
 536 
 537     /**
 538      * Checks if the specified unit is supported.
 539      * <p>
 540      * This checks if the specified unit can be added to, or subtracted from, this date.
 541      * If false, then calling the {@link #plus(long, TemporalUnit)} and
 542      * {@link #minus(long, TemporalUnit) minus} methods will throw an exception.
 543      * <p>
 544      * If the unit is a {@link ChronoUnit} then the query is implemented here.
 545      * The supported units are:
 546      * <ul>
 547      * <li>{@code DAYS}
 548      * <li>{@code WEEKS}
 549      * <li>{@code MONTHS}
 550      * <li>{@code YEARS}
 551      * <li>{@code DECADES}
 552      * <li>{@code CENTURIES}
 553      * <li>{@code MILLENNIA}
 554      * <li>{@code ERAS}
 555      * </ul>
 556      * All other {@code ChronoUnit} instances will return false.
 557      * <p>
 558      * If the unit is not a {@code ChronoUnit}, then the result of this method
 559      * is obtained by invoking {@code TemporalUnit.isSupportedBy(Temporal)}
 560      * passing {@code this} as the argument.
 561      * Whether the unit is supported is determined by the unit.
 562      *
 563      * @param unit  the unit to check, null returns false
 564      * @return true if the unit can be added/subtracted, false if not
 565      */
 566     @Override  // override for Javadoc
 567     public boolean isSupported(TemporalUnit unit) {
 568         return ChronoLocalDate.super.isSupported(unit);
 569     }
 570 
 571     //-----------------------------------------------------------------------
 572     /**
 573      * Gets the range of valid values for the specified field.
 574      * <p>
 575      * The range object expresses the minimum and maximum valid values for a field.
 576      * This date is used to enhance the accuracy of the returned range.
 577      * If it is not possible to return the range, because the field is not supported
 578      * or for some other reason, an exception is thrown.
 579      * <p>
 580      * If the field is a {@link ChronoField} then the query is implemented here.
 581      * The {@link #isSupported(TemporalField) supported fields} will return
 582      * appropriate range instances.
 583      * All other {@code ChronoField} instances will throw an {@code UnsupportedTemporalTypeException}.
 584      * <p>
 585      * If the field is not a {@code ChronoField}, then the result of this method
 586      * is obtained by invoking {@code TemporalField.rangeRefinedBy(TemporalAccessor)}
 587      * passing {@code this} as the argument.
 588      * Whether the range can be obtained is determined by the field.
 589      *
 590      * @param field  the field to query the range for, not null
 591      * @return the range of valid values for the field, not null
 592      * @throws DateTimeException if the range for the field cannot be obtained
 593      * @throws UnsupportedTemporalTypeException if the field is not supported
 594      */
 595     @Override
 596     public ValueRange range(TemporalField field) {
 597         if (field instanceof ChronoField chronoField) {
 598             if (chronoField.isDateBased()) {
 599                 return switch (chronoField) {
 600                     case DAY_OF_MONTH -> ValueRange.of(1, lengthOfMonth());
 601                     case DAY_OF_YEAR -> ValueRange.of(1, lengthOfYear());
 602                     case ALIGNED_WEEK_OF_MONTH -> ValueRange.of(1, getMonth() == Month.FEBRUARY && !isLeapYear() ? 4 : 5);
 603                     case YEAR_OF_ERA -> (getYear() <= 0 ? ValueRange.of(1, Year.MAX_VALUE + 1) : ValueRange.of(1, Year.MAX_VALUE));
 604                     default -> field.range();
 605                 };
 606             }
 607             throw new UnsupportedTemporalTypeException("Unsupported field: " + field);
 608         }
 609         return field.rangeRefinedBy(this);
 610     }
 611 
 612     /**
 613      * Gets the value of the specified field from this date as an {@code int}.
 614      * <p>
 615      * This queries this date for the value of the specified field.
 616      * The returned value will always be within the valid range of values for the field.
 617      * If it is not possible to return the value, because the field is not supported
 618      * or for some other reason, an exception is thrown.
 619      * <p>
 620      * If the field is a {@link ChronoField} then the query is implemented here.
 621      * The {@link #isSupported(TemporalField) supported fields} will return valid
 622      * values based on this date, except {@code EPOCH_DAY} and {@code PROLEPTIC_MONTH}
 623      * which are too large to fit in an {@code int} and throw an {@code UnsupportedTemporalTypeException}.
 624      * All other {@code ChronoField} instances will throw an {@code UnsupportedTemporalTypeException}.
 625      * <p>
 626      * If the field is not a {@code ChronoField}, then the result of this method
 627      * is obtained by invoking {@code TemporalField.getFrom(TemporalAccessor)}
 628      * passing {@code this} as the argument. Whether the value can be obtained,
 629      * and what the value represents, is determined by the field.
 630      *
 631      * @param field  the field to get, not null
 632      * @return the value for the field
 633      * @throws DateTimeException if a value for the field cannot be obtained or
 634      *         the value is outside the range of valid values for the field
 635      * @throws UnsupportedTemporalTypeException if the field is not supported or
 636      *         the range of values exceeds an {@code int}
 637      * @throws ArithmeticException if numeric overflow occurs
 638      */
 639     @Override  // override for Javadoc and performance
 640     public int get(TemporalField field) {
 641         if (field instanceof ChronoField) {
 642             return get0(field);
 643         }
 644         return ChronoLocalDate.super.get(field);
 645     }
 646 
 647     /**
 648      * Gets the value of the specified field from this date as a {@code long}.
 649      * <p>
 650      * This queries this date for the value of the specified field.
 651      * If it is not possible to return the value, because the field is not supported
 652      * or for some other reason, an exception is thrown.
 653      * <p>
 654      * If the field is a {@link ChronoField} then the query is implemented here.
 655      * The {@link #isSupported(TemporalField) supported fields} will return valid
 656      * values based on this date.
 657      * All other {@code ChronoField} instances will throw an {@code UnsupportedTemporalTypeException}.
 658      * <p>
 659      * If the field is not a {@code ChronoField}, then the result of this method
 660      * is obtained by invoking {@code TemporalField.getFrom(TemporalAccessor)}
 661      * passing {@code this} as the argument. Whether the value can be obtained,
 662      * and what the value represents, is determined by the field.
 663      *
 664      * @param field  the field to get, not null
 665      * @return the value for the field
 666      * @throws DateTimeException if a value for the field cannot be obtained
 667      * @throws UnsupportedTemporalTypeException if the field is not supported
 668      * @throws ArithmeticException if numeric overflow occurs
 669      */
 670     @Override
 671     public long getLong(TemporalField field) {
 672         if (field instanceof ChronoField) {
 673             if (field == EPOCH_DAY) {
 674                 return toEpochDay();
 675             }
 676             if (field == PROLEPTIC_MONTH) {
 677                 return getProlepticMonth();
 678             }
 679             return get0(field);
 680         }
 681         return field.getFrom(this);
 682     }
 683 
 684     private int get0(TemporalField field) {
 685         return switch ((ChronoField) field) {
 686             case DAY_OF_WEEK -> getDayOfWeek().getValue();
 687             case ALIGNED_DAY_OF_WEEK_IN_MONTH -> ((day - 1) % 7) + 1;
 688             case ALIGNED_DAY_OF_WEEK_IN_YEAR -> ((getDayOfYear() - 1) % 7) + 1;
 689             case DAY_OF_MONTH -> day;
 690             case DAY_OF_YEAR -> getDayOfYear();
 691             case EPOCH_DAY -> throw new UnsupportedTemporalTypeException("Invalid field 'EpochDay' for get() method, use getLong() instead");
 692             case ALIGNED_WEEK_OF_MONTH -> ((day - 1) / 7) + 1;
 693             case ALIGNED_WEEK_OF_YEAR -> ((getDayOfYear() - 1) / 7) + 1;
 694             case MONTH_OF_YEAR -> month;
 695             case PROLEPTIC_MONTH -> throw new UnsupportedTemporalTypeException("Invalid field 'ProlepticMonth' for get() method, use getLong() instead");
 696             case YEAR_OF_ERA -> (year >= 1 ? year : 1 - year);
 697             case YEAR -> year;
 698             case ERA -> (year >= 1 ? 1 : 0);
 699             default -> throw new UnsupportedTemporalTypeException("Unsupported field: " + field);
 700         };
 701     }
 702 
 703     private long getProlepticMonth() {
 704         return (year * 12L + month - 1);
 705     }
 706 
 707     //-----------------------------------------------------------------------
 708     /**
 709      * Gets the chronology of this date, which is the ISO calendar system.
 710      * <p>
 711      * The {@code Chronology} represents the calendar system in use.
 712      * The ISO-8601 calendar system is the modern civil calendar system used today
 713      * in most of the world. It is equivalent to the proleptic Gregorian calendar
 714      * system, in which today's rules for leap years are applied for all time.
 715      *
 716      * @return the ISO chronology, not null
 717      */
 718     @Override
 719     public IsoChronology getChronology() {
 720         return IsoChronology.INSTANCE;
 721     }
 722 
 723     /**
 724      * Gets the era applicable at this date.
 725      * <p>
 726      * The official ISO-8601 standard does not define eras, however {@code IsoChronology} does.
 727      * It defines two eras, 'CE' from year one onwards and 'BCE' from year zero backwards.
 728      * Since dates before the Julian-Gregorian cutover are not in line with history,
 729      * the cutover between 'BCE' and 'CE' is also not aligned with the commonly used
 730      * eras, often referred to using 'BC' and 'AD'.
 731      * <p>
 732      * Users of this class should typically ignore this method as it exists primarily
 733      * to fulfill the {@link ChronoLocalDate} contract where it is necessary to support
 734      * the Japanese calendar system.
 735      *
 736      * @return the IsoEra applicable at this date, not null
 737      */
 738     @Override // override for Javadoc
 739     public IsoEra getEra() {
 740         return (getYear() >= 1 ? IsoEra.CE : IsoEra.BCE);
 741     }
 742 
 743     /**
 744      * Gets the year field.
 745      * <p>
 746      * This method returns the primitive {@code int} value for the year.
 747      * <p>
 748      * The year returned by this method is proleptic as per {@code get(YEAR)}.
 749      * To obtain the year-of-era, use {@code get(YEAR_OF_ERA)}.
 750      *
 751      * @return the year, from MIN_YEAR to MAX_YEAR
 752      */
 753     public int getYear() {
 754         return year;
 755     }
 756 
 757     /**
 758      * Gets the month-of-year field from 1 to 12.
 759      * <p>
 760      * This method returns the month as an {@code int} from 1 to 12.
 761      * Application code is frequently clearer if the enum {@link Month}
 762      * is used by calling {@link #getMonth()}.
 763      *
 764      * @return the month-of-year, from 1 to 12
 765      * @see #getMonth()
 766      */
 767     public int getMonthValue() {
 768         return month;
 769     }
 770 
 771     /**
 772      * Gets the month-of-year field using the {@code Month} enum.
 773      * <p>
 774      * This method returns the enum {@link Month} for the month.
 775      * This avoids confusion as to what {@code int} values mean.
 776      * If you need access to the primitive {@code int} value then the enum
 777      * provides the {@link Month#getValue() int value}.
 778      *
 779      * @return the month-of-year, not null
 780      * @see #getMonthValue()
 781      */
 782     public Month getMonth() {
 783         return Month.of(month);
 784     }
 785 
 786     /**
 787      * Gets the day-of-month field.
 788      * <p>
 789      * This method returns the primitive {@code int} value for the day-of-month.
 790      *
 791      * @return the day-of-month, from 1 to 31
 792      */
 793     public int getDayOfMonth() {
 794         return day;
 795     }
 796 
 797     /**
 798      * Gets the day-of-year field.
 799      * <p>
 800      * This method returns the primitive {@code int} value for the day-of-year.
 801      *
 802      * @return the day-of-year, from 1 to 365, or 366 in a leap year
 803      */
 804     public int getDayOfYear() {
 805         return getMonth().firstDayOfYear(isLeapYear()) + day - 1;
 806     }
 807 
 808     /**
 809      * Gets the day-of-week field, which is an enum {@code DayOfWeek}.
 810      * <p>
 811      * This method returns the enum {@link DayOfWeek} for the day-of-week.
 812      * This avoids confusion as to what {@code int} values mean.
 813      * If you need access to the primitive {@code int} value then the enum
 814      * provides the {@link DayOfWeek#getValue() int value}.
 815      * <p>
 816      * Additional information can be obtained from the {@code DayOfWeek}.
 817      * This includes textual names of the values.
 818      *
 819      * @return the day-of-week, not null
 820      */
 821     public DayOfWeek getDayOfWeek() {
 822         int dow0 = Math.floorMod(toEpochDay() + 3, 7);
 823         return DayOfWeek.of(dow0 + 1);
 824     }
 825 
 826     //-----------------------------------------------------------------------
 827     /**
 828      * Checks if the year is a leap year, according to the ISO proleptic
 829      * calendar system rules.
 830      * <p>
 831      * This method applies the current rules for leap years across the whole time-line.
 832      * In general, a year is a leap year if it is divisible by four without
 833      * remainder. However, years divisible by 100, are not leap years, with
 834      * the exception of years divisible by 400 which are.
 835      * <p>
 836      * For example, 1904 is a leap year it is divisible by 4.
 837      * 1900 was not a leap year as it is divisible by 100, however 2000 was a
 838      * leap year as it is divisible by 400.
 839      * <p>
 840      * The calculation is proleptic - applying the same rules into the far future and far past.
 841      * This is historically inaccurate, but is correct for the ISO-8601 standard.
 842      *
 843      * @return true if the year is leap, false otherwise
 844      */
 845     @Override // override for Javadoc and performance
 846     public boolean isLeapYear() {
 847         return IsoChronology.INSTANCE.isLeapYear(year);
 848     }
 849 
 850     /**
 851      * Returns the length of the month represented by this date.
 852      * <p>
 853      * This returns the length of the month in days.
 854      * For example, a date in January would return 31.
 855      *
 856      * @return the length of the month in days
 857      */
 858     @Override
 859     public int lengthOfMonth() {
 860         return switch (month) {
 861             case 2 -> (isLeapYear() ? 29 : 28);
 862             case 4, 6, 9, 11 -> 30;
 863             default -> 31;
 864         };
 865     }
 866 
 867     /**
 868      * Returns the length of the year represented by this date.
 869      * <p>
 870      * This returns the length of the year in days, either 365 or 366.
 871      *
 872      * @return 366 if the year is leap, 365 otherwise
 873      */
 874     @Override // override for Javadoc and performance
 875     public int lengthOfYear() {
 876         return (isLeapYear() ? 366 : 365);
 877     }
 878 
 879     //-----------------------------------------------------------------------
 880     /**
 881      * Returns an adjusted copy of this date.
 882      * <p>
 883      * This returns a {@code LocalDate}, based on this one, with the date adjusted.
 884      * The adjustment takes place using the specified adjuster strategy object.
 885      * Read the documentation of the adjuster to understand what adjustment will be made.
 886      * <p>
 887      * A simple adjuster might simply set the one of the fields, such as the year field.
 888      * A more complex adjuster might set the date to the last day of the month.
 889      * <p>
 890      * A selection of common adjustments is provided in
 891      * {@link java.time.temporal.TemporalAdjusters TemporalAdjusters}.
 892      * These include finding the "last day of the month" and "next Wednesday".
 893      * Key date-time classes also implement the {@code TemporalAdjuster} interface,
 894      * such as {@link Month} and {@link java.time.MonthDay MonthDay}.
 895      * The adjuster is responsible for handling special cases, such as the varying
 896      * lengths of month and leap years.
 897      * <p>
 898      * For example this code returns a date on the last day of July:
 899      * <pre>
 900      *  import static java.time.Month.*;
 901      *  import static java.time.temporal.TemporalAdjusters.*;
 902      *
 903      *  result = localDate.with(JULY).with(lastDayOfMonth());
 904      * </pre>
 905      * <p>
 906      * The result of this method is obtained by invoking the
 907      * {@link TemporalAdjuster#adjustInto(Temporal)} method on the
 908      * specified adjuster passing {@code this} as the argument.
 909      * <p>
 910      * This instance is immutable and unaffected by this method call.
 911      *
 912      * @param adjuster the adjuster to use, not null
 913      * @return a {@code LocalDate} based on {@code this} with the adjustment made, not null
 914      * @throws DateTimeException if the adjustment cannot be made
 915      * @throws ArithmeticException if numeric overflow occurs
 916      */
 917     @Override
 918     public LocalDate with(TemporalAdjuster adjuster) {
 919         // optimizations
 920         if (adjuster instanceof LocalDate) {
 921             return (LocalDate) adjuster;
 922         }
 923         return (LocalDate) adjuster.adjustInto(this);
 924     }
 925 
 926     /**
 927      * Returns a copy of this date with the specified field set to a new value.
 928      * <p>
 929      * This returns a {@code LocalDate}, based on this one, with the value
 930      * for the specified field changed.
 931      * This can be used to change any supported field, such as the year, month or day-of-month.
 932      * If it is not possible to set the value, because the field is not supported or for
 933      * some other reason, an exception is thrown.
 934      * <p>
 935      * In some cases, changing the specified field can cause the resulting date to become invalid,
 936      * such as changing the month from 31st January to February would make the day-of-month invalid.
 937      * In cases like this, the field is responsible for resolving the date. Typically it will choose
 938      * the previous valid date, which would be the last valid day of February in this example.
 939      * <p>
 940      * If the field is a {@link ChronoField} then the adjustment is implemented here.
 941      * The supported fields behave as follows:
 942      * <ul>
 943      * <li>{@code DAY_OF_WEEK} -
 944      *  Returns a {@code LocalDate} with the specified day-of-week.
 945      *  The date is adjusted up to 6 days forward or backward within the boundary
 946      *  of a Monday to Sunday week.
 947      * <li>{@code ALIGNED_DAY_OF_WEEK_IN_MONTH} -
 948      *  Returns a {@code LocalDate} with the specified aligned-day-of-week.
 949      *  The date is adjusted to the specified month-based aligned-day-of-week.
 950      *  Aligned weeks are counted such that the first week of a given month starts
 951      *  on the first day of that month.
 952      *  This may cause the date to be moved up to 6 days into the following month.
 953      * <li>{@code ALIGNED_DAY_OF_WEEK_IN_YEAR} -
 954      *  Returns a {@code LocalDate} with the specified aligned-day-of-week.
 955      *  The date is adjusted to the specified year-based aligned-day-of-week.
 956      *  Aligned weeks are counted such that the first week of a given year starts
 957      *  on the first day of that year.
 958      *  This may cause the date to be moved up to 6 days into the following year.
 959      * <li>{@code DAY_OF_MONTH} -
 960      *  Returns a {@code LocalDate} with the specified day-of-month.
 961      *  The month and year will be unchanged. If the day-of-month is invalid for the
 962      *  year and month, then a {@code DateTimeException} is thrown.
 963      * <li>{@code DAY_OF_YEAR} -
 964      *  Returns a {@code LocalDate} with the specified day-of-year.
 965      *  The year will be unchanged. If the day-of-year is invalid for the
 966      *  year, then a {@code DateTimeException} is thrown.
 967      * <li>{@code EPOCH_DAY} -
 968      *  Returns a {@code LocalDate} with the specified epoch-day.
 969      *  This completely replaces the date and is equivalent to {@link #ofEpochDay(long)}.
 970      * <li>{@code ALIGNED_WEEK_OF_MONTH} -
 971      *  Returns a {@code LocalDate} with the specified aligned-week-of-month.
 972      *  Aligned weeks are counted such that the first week of a given month starts
 973      *  on the first day of that month.
 974      *  This adjustment moves the date in whole week chunks to match the specified week.
 975      *  The result will have the same day-of-week as this date.
 976      *  This may cause the date to be moved into the following month.
 977      * <li>{@code ALIGNED_WEEK_OF_YEAR} -
 978      *  Returns a {@code LocalDate} with the specified aligned-week-of-year.
 979      *  Aligned weeks are counted such that the first week of a given year starts
 980      *  on the first day of that year.
 981      *  This adjustment moves the date in whole week chunks to match the specified week.
 982      *  The result will have the same day-of-week as this date.
 983      *  This may cause the date to be moved into the following year.
 984      * <li>{@code MONTH_OF_YEAR} -
 985      *  Returns a {@code LocalDate} with the specified month-of-year.
 986      *  The year will be unchanged. The day-of-month will also be unchanged,
 987      *  unless it would be invalid for the new month and year. In that case, the
 988      *  day-of-month is adjusted to the maximum valid value for the new month and year.
 989      * <li>{@code PROLEPTIC_MONTH} -
 990      *  Returns a {@code LocalDate} with the specified proleptic-month.
 991      *  The day-of-month will be unchanged, unless it would be invalid for the new month
 992      *  and year. In that case, the day-of-month is adjusted to the maximum valid value
 993      *  for the new month and year.
 994      * <li>{@code YEAR_OF_ERA} -
 995      *  Returns a {@code LocalDate} with the specified year-of-era.
 996      *  The era and month will be unchanged. The day-of-month will also be unchanged,
 997      *  unless it would be invalid for the new month and year. In that case, the
 998      *  day-of-month is adjusted to the maximum valid value for the new month and year.
 999      * <li>{@code YEAR} -
1000      *  Returns a {@code LocalDate} with the specified year.
1001      *  The month will be unchanged. The day-of-month will also be unchanged,
1002      *  unless it would be invalid for the new month and year. In that case, the
1003      *  day-of-month is adjusted to the maximum valid value for the new month and year.
1004      * <li>{@code ERA} -
1005      *  Returns a {@code LocalDate} with the specified era.
1006      *  The year-of-era and month will be unchanged. The day-of-month will also be unchanged,
1007      *  unless it would be invalid for the new month and year. In that case, the
1008      *  day-of-month is adjusted to the maximum valid value for the new month and year.
1009      * </ul>
1010      * <p>
1011      * In all cases, if the new value is outside the valid range of values for the field
1012      * then a {@code DateTimeException} will be thrown.
1013      * <p>
1014      * All other {@code ChronoField} instances will throw an {@code UnsupportedTemporalTypeException}.
1015      * <p>
1016      * If the field is not a {@code ChronoField}, then the result of this method
1017      * is obtained by invoking {@code TemporalField.adjustInto(Temporal, long)}
1018      * passing {@code this} as the argument. In this case, the field determines
1019      * whether and how to adjust the instant.
1020      * <p>
1021      * This instance is immutable and unaffected by this method call.
1022      *
1023      * @param field  the field to set in the result, not null
1024      * @param newValue  the new value of the field in the result
1025      * @return a {@code LocalDate} based on {@code this} with the specified field set, not null
1026      * @throws DateTimeException if the field cannot be set
1027      * @throws UnsupportedTemporalTypeException if the field is not supported
1028      * @throws ArithmeticException if numeric overflow occurs
1029      */
1030     @Override
1031     public LocalDate with(TemporalField field, long newValue) {
1032         if (field instanceof ChronoField chronoField) {
1033             chronoField.checkValidValue(newValue);
1034             return switch (chronoField) {
1035                 case DAY_OF_WEEK -> plusDays(newValue - getDayOfWeek().getValue());
1036                 case ALIGNED_DAY_OF_WEEK_IN_MONTH -> plusDays(newValue - getLong(ALIGNED_DAY_OF_WEEK_IN_MONTH));
1037                 case ALIGNED_DAY_OF_WEEK_IN_YEAR -> plusDays(newValue - getLong(ALIGNED_DAY_OF_WEEK_IN_YEAR));
1038                 case DAY_OF_MONTH -> withDayOfMonth((int) newValue);
1039                 case DAY_OF_YEAR -> withDayOfYear((int) newValue);
1040                 case EPOCH_DAY -> LocalDate.ofEpochDay(newValue);
1041                 case ALIGNED_WEEK_OF_MONTH -> plusWeeks(newValue - getLong(ALIGNED_WEEK_OF_MONTH));
1042                 case ALIGNED_WEEK_OF_YEAR -> plusWeeks(newValue - getLong(ALIGNED_WEEK_OF_YEAR));
1043                 case MONTH_OF_YEAR -> withMonth((int) newValue);
1044                 case PROLEPTIC_MONTH -> plusMonths(newValue - getProlepticMonth());
1045                 case YEAR_OF_ERA -> withYear((int) (year >= 1 ? newValue : 1 - newValue));
1046                 case YEAR -> withYear((int) newValue);
1047                 case ERA -> (getLong(ERA) == newValue ? this : withYear(1 - year));
1048                 default -> throw new UnsupportedTemporalTypeException("Unsupported field: " + field);
1049             };
1050         }
1051         return field.adjustInto(this, newValue);
1052     }
1053 
1054     //-----------------------------------------------------------------------
1055     /**
1056      * Returns a copy of this {@code LocalDate} with the year altered.
1057      * <p>
1058      * If the day-of-month is invalid for the year, it will be changed to the last valid day of the month.
1059      * <p>
1060      * This instance is immutable and unaffected by this method call.
1061      *
1062      * @param year  the year to set in the result, from MIN_YEAR to MAX_YEAR
1063      * @return a {@code LocalDate} based on this date with the requested year, not null
1064      * @throws DateTimeException if the year value is invalid
1065      */
1066     public LocalDate withYear(int year) {
1067         if (this.year == year) {
1068             return this;
1069         }
1070         YEAR.checkValidValue(year);
1071         return resolvePreviousValid(year, month, day);
1072     }
1073 
1074     /**
1075      * Returns a copy of this {@code LocalDate} with the month-of-year altered.
1076      * <p>
1077      * If the day-of-month is invalid for the year, it will be changed to the last valid day of the month.
1078      * <p>
1079      * This instance is immutable and unaffected by this method call.
1080      *
1081      * @param month  the month-of-year to set in the result, from 1 (January) to 12 (December)
1082      * @return a {@code LocalDate} based on this date with the requested month, not null
1083      * @throws DateTimeException if the month-of-year value is invalid
1084      */
1085     public LocalDate withMonth(int month) {
1086         if (this.month == month) {
1087             return this;
1088         }
1089         MONTH_OF_YEAR.checkValidValue(month);
1090         return resolvePreviousValid(year, month, day);
1091     }
1092 
1093     /**
1094      * Returns a copy of this {@code LocalDate} with the day-of-month altered.
1095      * <p>
1096      * If the resulting date is invalid, an exception is thrown.
1097      * <p>
1098      * This instance is immutable and unaffected by this method call.
1099      *
1100      * @param dayOfMonth  the day-of-month to set in the result, from 1 to 28-31
1101      * @return a {@code LocalDate} based on this date with the requested day, not null
1102      * @throws DateTimeException if the day-of-month value is invalid,
1103      *  or if the day-of-month is invalid for the month-year
1104      */
1105     public LocalDate withDayOfMonth(int dayOfMonth) {
1106         if (this.day == dayOfMonth) {
1107             return this;
1108         }
1109         return of(year, month, dayOfMonth);
1110     }
1111 
1112     /**
1113      * Returns a copy of this {@code LocalDate} with the day-of-year altered.
1114      * <p>
1115      * If the resulting date is invalid, an exception is thrown.
1116      * <p>
1117      * This instance is immutable and unaffected by this method call.
1118      *
1119      * @param dayOfYear  the day-of-year to set in the result, from 1 to 365-366
1120      * @return a {@code LocalDate} based on this date with the requested day, not null
1121      * @throws DateTimeException if the day-of-year value is invalid,
1122      *  or if the day-of-year is invalid for the year
1123      */
1124     public LocalDate withDayOfYear(int dayOfYear) {
1125         if (this.getDayOfYear() == dayOfYear) {
1126             return this;
1127         }
1128         return ofYearDay(year, dayOfYear);
1129     }
1130 
1131     //-----------------------------------------------------------------------
1132     /**
1133      * Returns a copy of this date with the specified amount added.
1134      * <p>
1135      * This returns a {@code LocalDate}, based on this one, with the specified amount added.
1136      * The amount is typically {@link Period} but may be any other type implementing
1137      * the {@link TemporalAmount} interface.
1138      * <p>
1139      * The calculation is delegated to the amount object by calling
1140      * {@link TemporalAmount#addTo(Temporal)}. The amount implementation is free
1141      * to implement the addition in any way it wishes, however it typically
1142      * calls back to {@link #plus(long, TemporalUnit)}. Consult the documentation
1143      * of the amount implementation to determine if it can be successfully added.
1144      * <p>
1145      * This instance is immutable and unaffected by this method call.
1146      *
1147      * @param amountToAdd  the amount to add, not null
1148      * @return a {@code LocalDate} based on this date with the addition made, not null
1149      * @throws DateTimeException if the addition cannot be made
1150      * @throws ArithmeticException if numeric overflow occurs
1151      */
1152     @Override
1153     public LocalDate plus(TemporalAmount amountToAdd) {
1154         if (amountToAdd instanceof Period periodToAdd) {
1155             return plusMonths(periodToAdd.toTotalMonths()).plusDays(periodToAdd.getDays());
1156         }
1157         Objects.requireNonNull(amountToAdd, "amountToAdd");
1158         return (LocalDate) amountToAdd.addTo(this);
1159     }
1160 
1161     /**
1162      * Returns a copy of this date with the specified amount added.
1163      * <p>
1164      * This returns a {@code LocalDate}, based on this one, with the amount
1165      * in terms of the unit added. If it is not possible to add the amount, because the
1166      * unit is not supported or for some other reason, an exception is thrown.
1167      * <p>
1168      * In some cases, adding the amount can cause the resulting date to become invalid.
1169      * For example, adding one month to 31st January would result in 31st February.
1170      * In cases like this, the unit is responsible for resolving the date.
1171      * Typically it will choose the previous valid date, which would be the last valid
1172      * day of February in this example.
1173      * <p>
1174      * If the field is a {@link ChronoUnit} then the addition is implemented here.
1175      * The supported fields behave as follows:
1176      * <ul>
1177      * <li>{@code DAYS} -
1178      *  Returns a {@code LocalDate} with the specified number of days added.
1179      *  This is equivalent to {@link #plusDays(long)}.
1180      * <li>{@code WEEKS} -
1181      *  Returns a {@code LocalDate} with the specified number of weeks added.
1182      *  This is equivalent to {@link #plusWeeks(long)} and uses a 7 day week.
1183      * <li>{@code MONTHS} -
1184      *  Returns a {@code LocalDate} with the specified number of months added.
1185      *  This is equivalent to {@link #plusMonths(long)}.
1186      *  The day-of-month will be unchanged unless it would be invalid for the new
1187      *  month and year. In that case, the day-of-month is adjusted to the maximum
1188      *  valid value for the new month and year.
1189      * <li>{@code YEARS} -
1190      *  Returns a {@code LocalDate} with the specified number of years added.
1191      *  This is equivalent to {@link #plusYears(long)}.
1192      *  The day-of-month will be unchanged unless it would be invalid for the new
1193      *  month and year. In that case, the day-of-month is adjusted to the maximum
1194      *  valid value for the new month and year.
1195      * <li>{@code DECADES} -
1196      *  Returns a {@code LocalDate} with the specified number of decades added.
1197      *  This is equivalent to calling {@link #plusYears(long)} with the amount
1198      *  multiplied by 10.
1199      *  The day-of-month will be unchanged unless it would be invalid for the new
1200      *  month and year. In that case, the day-of-month is adjusted to the maximum
1201      *  valid value for the new month and year.
1202      * <li>{@code CENTURIES} -
1203      *  Returns a {@code LocalDate} with the specified number of centuries added.
1204      *  This is equivalent to calling {@link #plusYears(long)} with the amount
1205      *  multiplied by 100.
1206      *  The day-of-month will be unchanged unless it would be invalid for the new
1207      *  month and year. In that case, the day-of-month is adjusted to the maximum
1208      *  valid value for the new month and year.
1209      * <li>{@code MILLENNIA} -
1210      *  Returns a {@code LocalDate} with the specified number of millennia added.
1211      *  This is equivalent to calling {@link #plusYears(long)} with the amount
1212      *  multiplied by 1,000.
1213      *  The day-of-month will be unchanged unless it would be invalid for the new
1214      *  month and year. In that case, the day-of-month is adjusted to the maximum
1215      *  valid value for the new month and year.
1216      * <li>{@code ERAS} -
1217      *  Returns a {@code LocalDate} with the specified number of eras added.
1218      *  Only two eras are supported so the amount must be one, zero or minus one.
1219      *  If the amount is non-zero then the year is changed such that the year-of-era
1220      *  is unchanged.
1221      *  The day-of-month will be unchanged unless it would be invalid for the new
1222      *  month and year. In that case, the day-of-month is adjusted to the maximum
1223      *  valid value for the new month and year.
1224      * </ul>
1225      * <p>
1226      * All other {@code ChronoUnit} instances will throw an {@code UnsupportedTemporalTypeException}.
1227      * <p>
1228      * If the field is not a {@code ChronoUnit}, then the result of this method
1229      * is obtained by invoking {@code TemporalUnit.addTo(Temporal, long)}
1230      * passing {@code this} as the argument. In this case, the unit determines
1231      * whether and how to perform the addition.
1232      * <p>
1233      * This instance is immutable and unaffected by this method call.
1234      *
1235      * @param amountToAdd  the amount of the unit to add to the result, may be negative
1236      * @param unit  the unit of the amount to add, not null
1237      * @return a {@code LocalDate} based on this date with the specified amount added, not null
1238      * @throws DateTimeException if the addition cannot be made
1239      * @throws UnsupportedTemporalTypeException if the unit is not supported
1240      * @throws ArithmeticException if numeric overflow occurs
1241      */
1242     @Override
1243     public LocalDate plus(long amountToAdd, TemporalUnit unit) {
1244         if (unit instanceof ChronoUnit chronoUnit) {
1245             return switch (chronoUnit) {
1246                 case DAYS      -> plusDays(amountToAdd);
1247                 case WEEKS     -> plusWeeks(amountToAdd);
1248                 case MONTHS    -> plusMonths(amountToAdd);
1249                 case YEARS     -> plusYears(amountToAdd);
1250                 case DECADES   -> plusYears(Math.multiplyExact(amountToAdd, 10));
1251                 case CENTURIES -> plusYears(Math.multiplyExact(amountToAdd, 100));
1252                 case MILLENNIA -> plusYears(Math.multiplyExact(amountToAdd, 1000));
1253                 case ERAS      -> with(ERA, Math.addExact(getLong(ERA), amountToAdd));
1254                 default -> throw new UnsupportedTemporalTypeException("Unsupported unit: " + unit);
1255             };
1256         }
1257         return unit.addTo(this, amountToAdd);
1258     }
1259 
1260     //-----------------------------------------------------------------------
1261     /**
1262      * Returns a copy of this {@code LocalDate} with the specified number of years added.
1263      * <p>
1264      * This method adds the specified amount to the years field in three steps:
1265      * <ol>
1266      * <li>Add the input years to the year field</li>
1267      * <li>Check if the resulting date would be invalid</li>
1268      * <li>Adjust the day-of-month to the last valid day if necessary</li>
1269      * </ol>
1270      * <p>
1271      * For example, 2008-02-29 (leap year) plus one year would result in the
1272      * invalid date 2009-02-29 (standard year). Instead of returning an invalid
1273      * result, the last valid day of the month, 2009-02-28, is selected instead.
1274      * <p>
1275      * This instance is immutable and unaffected by this method call.
1276      *
1277      * @param yearsToAdd  the years to add, may be negative
1278      * @return a {@code LocalDate} based on this date with the years added, not null
1279      * @throws DateTimeException if the result exceeds the supported date range
1280      */
1281     public LocalDate plusYears(long yearsToAdd) {
1282         if (yearsToAdd == 0) {
1283             return this;
1284         }
1285         int newYear = YEAR.checkValidIntValue(year + yearsToAdd);  // safe overflow
1286         return resolvePreviousValid(newYear, month, day);
1287     }
1288 
1289     /**
1290      * Returns a copy of this {@code LocalDate} with the specified number of months added.
1291      * <p>
1292      * This method adds the specified amount to the months field in three steps:
1293      * <ol>
1294      * <li>Add the input months to the month-of-year field</li>
1295      * <li>Check if the resulting date would be invalid</li>
1296      * <li>Adjust the day-of-month to the last valid day if necessary</li>
1297      * </ol>
1298      * <p>
1299      * For example, 2007-03-31 plus one month would result in the invalid date
1300      * 2007-04-31. Instead of returning an invalid result, the last valid day
1301      * of the month, 2007-04-30, is selected instead.
1302      * <p>
1303      * This instance is immutable and unaffected by this method call.
1304      *
1305      * @param monthsToAdd  the months to add, may be negative
1306      * @return a {@code LocalDate} based on this date with the months added, not null
1307      * @throws DateTimeException if the result exceeds the supported date range
1308      */
1309     public LocalDate plusMonths(long monthsToAdd) {
1310         if (monthsToAdd == 0) {
1311             return this;
1312         }
1313         long monthCount = year * 12L + (month - 1);
1314         long calcMonths = monthCount + monthsToAdd;  // safe overflow
1315         int newYear = YEAR.checkValidIntValue(Math.floorDiv(calcMonths, 12));
1316         int newMonth = Math.floorMod(calcMonths, 12) + 1;
1317         return resolvePreviousValid(newYear, newMonth, day);
1318     }
1319 
1320     /**
1321      * Returns a copy of this {@code LocalDate} with the specified number of weeks added.
1322      * <p>
1323      * This method adds the specified amount in weeks to the days field incrementing
1324      * the month and year fields as necessary to ensure the result remains valid.
1325      * The result is only invalid if the maximum/minimum year is exceeded.
1326      * <p>
1327      * For example, 2008-12-31 plus one week would result in 2009-01-07.
1328      * <p>
1329      * This instance is immutable and unaffected by this method call.
1330      *
1331      * @param weeksToAdd  the weeks to add, may be negative
1332      * @return a {@code LocalDate} based on this date with the weeks added, not null
1333      * @throws DateTimeException if the result exceeds the supported date range
1334      */
1335     public LocalDate plusWeeks(long weeksToAdd) {
1336         return plusDays(Math.multiplyExact(weeksToAdd, 7));
1337     }
1338 
1339     /**
1340      * Returns a copy of this {@code LocalDate} with the specified number of days added.
1341      * <p>
1342      * This method adds the specified amount to the days field incrementing the
1343      * month and year fields as necessary to ensure the result remains valid.
1344      * The result is only invalid if the maximum/minimum year is exceeded.
1345      * <p>
1346      * For example, 2008-12-31 plus one day would result in 2009-01-01.
1347      * <p>
1348      * This instance is immutable and unaffected by this method call.
1349      *
1350      * @param daysToAdd  the days to add, may be negative
1351      * @return a {@code LocalDate} based on this date with the days added, not null
1352      * @throws DateTimeException if the result exceeds the supported date range
1353      */
1354     public LocalDate plusDays(long daysToAdd) {
1355         if (daysToAdd == 0) {
1356             return this;
1357         }
1358         long dom = day + daysToAdd;
1359         if (dom > 0) {
1360             if (dom <= 28) {
1361                 return new LocalDate(year, month, (int) dom);
1362             } else if (dom <= 59) { // 59th Jan is 28th Feb, 59th Feb is 31st Mar
1363                 long monthLen = lengthOfMonth();
1364                 if (dom <= monthLen) {
1365                     return new LocalDate(year, month, (int) dom);
1366                 } else if (month < 12) {
1367                     return new LocalDate(year, month + 1, (int) (dom - monthLen));
1368                 } else {
1369                     YEAR.checkValidValue(year + 1);
1370                     return new LocalDate(year + 1, 1, (int) (dom - monthLen));
1371                 }
1372             }
1373         }
1374 
1375         long mjDay = Math.addExact(toEpochDay(), daysToAdd);
1376         return LocalDate.ofEpochDay(mjDay);
1377     }
1378 
1379     //-----------------------------------------------------------------------
1380     /**
1381      * Returns a copy of this date with the specified amount subtracted.
1382      * <p>
1383      * This returns a {@code LocalDate}, based on this one, with the specified amount subtracted.
1384      * The amount is typically {@link Period} but may be any other type implementing
1385      * the {@link TemporalAmount} interface.
1386      * <p>
1387      * The calculation is delegated to the amount object by calling
1388      * {@link TemporalAmount#subtractFrom(Temporal)}. The amount implementation is free
1389      * to implement the subtraction in any way it wishes, however it typically
1390      * calls back to {@link #minus(long, TemporalUnit)}. Consult the documentation
1391      * of the amount implementation to determine if it can be successfully subtracted.
1392      * <p>
1393      * This instance is immutable and unaffected by this method call.
1394      *
1395      * @param amountToSubtract  the amount to subtract, not null
1396      * @return a {@code LocalDate} based on this date with the subtraction made, not null
1397      * @throws DateTimeException if the subtraction cannot be made
1398      * @throws ArithmeticException if numeric overflow occurs
1399      */
1400     @Override
1401     public LocalDate minus(TemporalAmount amountToSubtract) {
1402         if (amountToSubtract instanceof Period periodToSubtract) {
1403             return minusMonths(periodToSubtract.toTotalMonths()).minusDays(periodToSubtract.getDays());
1404         }
1405         Objects.requireNonNull(amountToSubtract, "amountToSubtract");
1406         return (LocalDate) amountToSubtract.subtractFrom(this);
1407     }
1408 
1409     /**
1410      * Returns a copy of this date with the specified amount subtracted.
1411      * <p>
1412      * This returns a {@code LocalDate}, based on this one, with the amount
1413      * in terms of the unit subtracted. If it is not possible to subtract the amount,
1414      * because the unit is not supported or for some other reason, an exception is thrown.
1415      * <p>
1416      * This method is equivalent to {@link #plus(long, TemporalUnit)} with the amount negated.
1417      * See that method for a full description of how addition, and thus subtraction, works.
1418      * <p>
1419      * This instance is immutable and unaffected by this method call.
1420      *
1421      * @param amountToSubtract  the amount of the unit to subtract from the result, may be negative
1422      * @param unit  the unit of the amount to subtract, not null
1423      * @return a {@code LocalDate} based on this date with the specified amount subtracted, not null
1424      * @throws DateTimeException if the subtraction cannot be made
1425      * @throws UnsupportedTemporalTypeException if the unit is not supported
1426      * @throws ArithmeticException if numeric overflow occurs
1427      */
1428     @Override
1429     public LocalDate minus(long amountToSubtract, TemporalUnit unit) {
1430         return (amountToSubtract == Long.MIN_VALUE ? plus(Long.MAX_VALUE, unit).plus(1, unit) : plus(-amountToSubtract, unit));
1431     }
1432 
1433     //-----------------------------------------------------------------------
1434     /**
1435      * Returns a copy of this {@code LocalDate} with the specified number of years subtracted.
1436      * <p>
1437      * This method subtracts the specified amount from the years field in three steps:
1438      * <ol>
1439      * <li>Subtract the input years from the year field</li>
1440      * <li>Check if the resulting date would be invalid</li>
1441      * <li>Adjust the day-of-month to the last valid day if necessary</li>
1442      * </ol>
1443      * <p>
1444      * For example, 2008-02-29 (leap year) minus one year would result in the
1445      * invalid date 2007-02-29 (standard year). Instead of returning an invalid
1446      * result, the last valid day of the month, 2007-02-28, is selected instead.
1447      * <p>
1448      * This instance is immutable and unaffected by this method call.
1449      *
1450      * @param yearsToSubtract  the years to subtract, may be negative
1451      * @return a {@code LocalDate} based on this date with the years subtracted, not null
1452      * @throws DateTimeException if the result exceeds the supported date range
1453      */
1454     public LocalDate minusYears(long yearsToSubtract) {
1455         return (yearsToSubtract == Long.MIN_VALUE ? plusYears(Long.MAX_VALUE).plusYears(1) : plusYears(-yearsToSubtract));
1456     }
1457 
1458     /**
1459      * Returns a copy of this {@code LocalDate} with the specified number of months subtracted.
1460      * <p>
1461      * This method subtracts the specified amount from the months field in three steps:
1462      * <ol>
1463      * <li>Subtract the input months from the month-of-year field</li>
1464      * <li>Check if the resulting date would be invalid</li>
1465      * <li>Adjust the day-of-month to the last valid day if necessary</li>
1466      * </ol>
1467      * <p>
1468      * For example, 2007-03-31 minus one month would result in the invalid date
1469      * 2007-02-31. Instead of returning an invalid result, the last valid day
1470      * of the month, 2007-02-28, is selected instead.
1471      * <p>
1472      * This instance is immutable and unaffected by this method call.
1473      *
1474      * @param monthsToSubtract  the months to subtract, may be negative
1475      * @return a {@code LocalDate} based on this date with the months subtracted, not null
1476      * @throws DateTimeException if the result exceeds the supported date range
1477      */
1478     public LocalDate minusMonths(long monthsToSubtract) {
1479         return (monthsToSubtract == Long.MIN_VALUE ? plusMonths(Long.MAX_VALUE).plusMonths(1) : plusMonths(-monthsToSubtract));
1480     }
1481 
1482     /**
1483      * Returns a copy of this {@code LocalDate} with the specified number of weeks subtracted.
1484      * <p>
1485      * This method subtracts the specified amount in weeks from the days field decrementing
1486      * the month and year fields as necessary to ensure the result remains valid.
1487      * The result is only invalid if the maximum/minimum year is exceeded.
1488      * <p>
1489      * For example, 2009-01-07 minus one week would result in 2008-12-31.
1490      * <p>
1491      * This instance is immutable and unaffected by this method call.
1492      *
1493      * @param weeksToSubtract  the weeks to subtract, may be negative
1494      * @return a {@code LocalDate} based on this date with the weeks subtracted, not null
1495      * @throws DateTimeException if the result exceeds the supported date range
1496      */
1497     public LocalDate minusWeeks(long weeksToSubtract) {
1498         return (weeksToSubtract == Long.MIN_VALUE ? plusWeeks(Long.MAX_VALUE).plusWeeks(1) : plusWeeks(-weeksToSubtract));
1499     }
1500 
1501     /**
1502      * Returns a copy of this {@code LocalDate} with the specified number of days subtracted.
1503      * <p>
1504      * This method subtracts the specified amount from the days field decrementing the
1505      * month and year fields as necessary to ensure the result remains valid.
1506      * The result is only invalid if the maximum/minimum year is exceeded.
1507      * <p>
1508      * For example, 2009-01-01 minus one day would result in 2008-12-31.
1509      * <p>
1510      * This instance is immutable and unaffected by this method call.
1511      *
1512      * @param daysToSubtract  the days to subtract, may be negative
1513      * @return a {@code LocalDate} based on this date with the days subtracted, not null
1514      * @throws DateTimeException if the result exceeds the supported date range
1515      */
1516     public LocalDate minusDays(long daysToSubtract) {
1517         return (daysToSubtract == Long.MIN_VALUE ? plusDays(Long.MAX_VALUE).plusDays(1) : plusDays(-daysToSubtract));
1518     }
1519 
1520     //-----------------------------------------------------------------------
1521     /**
1522      * Queries this date using the specified query.
1523      * <p>
1524      * This queries this date using the specified query strategy object.
1525      * The {@code TemporalQuery} object defines the logic to be used to
1526      * obtain the result. Read the documentation of the query to understand
1527      * what the result of this method will be.
1528      * <p>
1529      * The result of this method is obtained by invoking the
1530      * {@link TemporalQuery#queryFrom(TemporalAccessor)} method on the
1531      * specified query passing {@code this} as the argument.
1532      *
1533      * @param <R> the type of the result
1534      * @param query  the query to invoke, not null
1535      * @return the query result, null may be returned (defined by the query)
1536      * @throws DateTimeException if unable to query (defined by the query)
1537      * @throws ArithmeticException if numeric overflow occurs (defined by the query)
1538      */
1539     @SuppressWarnings("unchecked")
1540     @Override
1541     public <R> R query(TemporalQuery<R> query) {
1542         if (query == TemporalQueries.localDate()) {
1543             return (R) this;
1544         }
1545         return ChronoLocalDate.super.query(query);
1546     }
1547 
1548     /**
1549      * Adjusts the specified temporal object to have the same date as this object.
1550      * <p>
1551      * This returns a temporal object of the same observable type as the input
1552      * with the date changed to be the same as this.
1553      * <p>
1554      * The adjustment is equivalent to using {@link Temporal#with(TemporalField, long)}
1555      * passing {@link ChronoField#EPOCH_DAY} as the field.
1556      * <p>
1557      * In most cases, it is clearer to reverse the calling pattern by using
1558      * {@link Temporal#with(TemporalAdjuster)}:
1559      * <pre>
1560      *   // these two lines are equivalent, but the second approach is recommended
1561      *   temporal = thisLocalDate.adjustInto(temporal);
1562      *   temporal = temporal.with(thisLocalDate);
1563      * </pre>
1564      * <p>
1565      * This instance is immutable and unaffected by this method call.
1566      *
1567      * @param temporal  the target object to be adjusted, not null
1568      * @return the adjusted object, not null
1569      * @throws DateTimeException if unable to make the adjustment
1570      * @throws ArithmeticException if numeric overflow occurs
1571      */
1572     @Override  // override for Javadoc
1573     public Temporal adjustInto(Temporal temporal) {
1574         return ChronoLocalDate.super.adjustInto(temporal);
1575     }
1576 
1577     /**
1578      * Calculates the amount of time until another date in terms of the specified unit.
1579      * <p>
1580      * This calculates the amount of time between two {@code LocalDate}
1581      * objects in terms of a single {@code TemporalUnit}.
1582      * The start and end points are {@code this} and the specified date.
1583      * The result will be negative if the end is before the start.
1584      * The {@code Temporal} passed to this method is converted to a
1585      * {@code LocalDate} using {@link #from(TemporalAccessor)}.
1586      * For example, the amount in days between two dates can be calculated
1587      * using {@code startDate.until(endDate, DAYS)}.
1588      * <p>
1589      * The calculation returns a whole number, representing the number of
1590      * complete units between the two dates.
1591      * For example, the amount in months between 2012-06-15 and 2012-08-14
1592      * will only be one month as it is one day short of two months.
1593      * <p>
1594      * There are two equivalent ways of using this method.
1595      * The first is to invoke this method.
1596      * The second is to use {@link TemporalUnit#between(Temporal, Temporal)}:
1597      * <pre>
1598      *   // these two lines are equivalent
1599      *   amount = start.until(end, MONTHS);
1600      *   amount = MONTHS.between(start, end);
1601      * </pre>
1602      * The choice should be made based on which makes the code more readable.
1603      * <p>
1604      * The calculation is implemented in this method for {@link ChronoUnit}.
1605      * The units {@code DAYS}, {@code WEEKS}, {@code MONTHS}, {@code YEARS},
1606      * {@code DECADES}, {@code CENTURIES}, {@code MILLENNIA} and {@code ERAS}
1607      * are supported. Other {@code ChronoUnit} values will throw an exception.
1608      * <p>
1609      * If the unit is not a {@code ChronoUnit}, then the result of this method
1610      * is obtained by invoking {@code TemporalUnit.between(Temporal, Temporal)}
1611      * passing {@code this} as the first argument and the converted input temporal
1612      * as the second argument.
1613      * <p>
1614      * This instance is immutable and unaffected by this method call.
1615      *
1616      * @param endExclusive  the end date, exclusive, which is converted to a {@code LocalDate}, not null
1617      * @param unit  the unit to measure the amount in, not null
1618      * @return the amount of time between this date and the end date
1619      * @throws DateTimeException if the amount cannot be calculated, or the end
1620      *  temporal cannot be converted to a {@code LocalDate}
1621      * @throws UnsupportedTemporalTypeException if the unit is not supported
1622      * @throws ArithmeticException if numeric overflow occurs
1623      */
1624     @Override
1625     public long until(Temporal endExclusive, TemporalUnit unit) {
1626         LocalDate end = LocalDate.from(endExclusive);
1627         if (unit instanceof ChronoUnit chronoUnit) {
1628             return switch (chronoUnit) {
1629                 case DAYS      -> daysUntil(end);
1630                 case WEEKS     -> daysUntil(end) / 7;
1631                 case MONTHS    -> monthsUntil(end);
1632                 case YEARS     -> monthsUntil(end) / 12;
1633                 case DECADES   -> monthsUntil(end) / 120;
1634                 case CENTURIES -> monthsUntil(end) / 1200;
1635                 case MILLENNIA -> monthsUntil(end) / 12000;
1636                 case ERAS      -> end.getLong(ERA) - getLong(ERA);
1637                 default -> throw new UnsupportedTemporalTypeException("Unsupported unit: " + unit);
1638             };
1639         }
1640         return unit.between(this, end);
1641     }
1642 
1643     long daysUntil(LocalDate end) {
1644         return end.toEpochDay() - toEpochDay();  // no overflow
1645     }
1646 
1647     private long monthsUntil(LocalDate end) {
1648         long packed1 = getProlepticMonth() * 32L + getDayOfMonth();  // no overflow
1649         long packed2 = end.getProlepticMonth() * 32L + end.getDayOfMonth();  // no overflow
1650         return (packed2 - packed1) / 32;
1651     }
1652 
1653     /**
1654      * Calculates the period between this date and another date as a {@code Period}.
1655      * <p>
1656      * This calculates the period between two dates in terms of years, months and days.
1657      * The start and end points are {@code this} and the specified date.
1658      * The result will be negative if the end is before the start.
1659      * The negative sign will be the same in each of year, month and day.
1660      * <p>
1661      * The calculation is performed using the ISO calendar system.
1662      * If necessary, the input date will be converted to ISO.
1663      * <p>
1664      * The start date is included, but the end date is not.
1665      * The period is calculated by removing complete months, then calculating
1666      * the remaining number of days, adjusting to ensure that both have the same sign.
1667      * The number of months is then normalized into years and months based on a 12 month year.
1668      * A month is considered to be complete if the end day-of-month is greater
1669      * than or equal to the start day-of-month.
1670      * For example, from {@code 2010-01-15} to {@code 2011-03-18} is "1 year, 2 months and 3 days".
1671      * <p>
1672      * There are two equivalent ways of using this method.
1673      * The first is to invoke this method.
1674      * The second is to use {@link Period#between(LocalDate, LocalDate)}:
1675      * <pre>
1676      *   // these two lines are equivalent
1677      *   period = start.until(end);
1678      *   period = Period.between(start, end);
1679      * </pre>
1680      * The choice should be made based on which makes the code more readable.
1681      *
1682      * @param endDateExclusive  the end date, exclusive, which may be in any chronology, not null
1683      * @return the period between this date and the end date, not null
1684      */
1685     @Override
1686     public Period until(ChronoLocalDate endDateExclusive) {
1687         LocalDate end = LocalDate.from(endDateExclusive);
1688         long totalMonths = end.getProlepticMonth() - this.getProlepticMonth();  // safe
1689         int days = end.day - this.day;
1690         if (totalMonths > 0 && days < 0) {
1691             totalMonths--;
1692             LocalDate calcDate = this.plusMonths(totalMonths);
1693             days = (int) (end.toEpochDay() - calcDate.toEpochDay());  // safe
1694         } else if (totalMonths < 0 && days > 0) {
1695             totalMonths++;
1696             days -= end.lengthOfMonth();
1697         }
1698         long years = totalMonths / 12;  // safe
1699         int months = (int) (totalMonths % 12);  // safe
1700         return Period.of(Math.toIntExact(years), months, days);
1701     }
1702 
1703     /**
1704      * Returns a sequential ordered stream of dates. The returned stream starts from this date
1705      * (inclusive) and goes to {@code endExclusive} (exclusive) by an incremental step of 1 day.
1706      * <p>
1707      * This method is equivalent to {@code datesUntil(endExclusive, Period.ofDays(1))}.
1708      *
1709      * @param endExclusive  the end date, exclusive, not null
1710      * @return a sequential {@code Stream} for the range of {@code LocalDate} values
1711      * @throws IllegalArgumentException if end date is before this date
1712      * @since 9
1713      */
1714     public Stream<LocalDate> datesUntil(LocalDate endExclusive) {
1715         long end = endExclusive.toEpochDay();
1716         long start = toEpochDay();
1717         if (end < start) {
1718             throw new IllegalArgumentException(endExclusive + " < " + this);
1719         }
1720         return LongStream.range(start, end).mapToObj(LocalDate::ofEpochDay);
1721     }
1722 
1723     /**
1724      * Returns a sequential ordered stream of dates by given incremental step. The returned stream
1725      * starts from this date (inclusive) and goes to {@code endExclusive} (exclusive).
1726      * <p>
1727      * The n-th date which appears in the stream is equal to {@code this.plus(step.multipliedBy(n))}
1728      * (but the result of step multiplication never overflows). For example, if this date is
1729      * {@code 2015-01-31}, the end date is {@code 2015-05-01} and the step is 1 month, then the
1730      * stream contains {@code 2015-01-31}, {@code 2015-02-28}, {@code 2015-03-31}, and
1731      * {@code 2015-04-30}.
1732      *
1733      * @param endExclusive  the end date, exclusive, not null
1734      * @param step  the non-zero, non-negative {@code Period} which represents the step.
1735      * @return a sequential {@code Stream} for the range of {@code LocalDate} values
1736      * @throws IllegalArgumentException if step is zero, or {@code step.getDays()} and
1737      *             {@code step.toTotalMonths()} have opposite sign, or end date is before this date
1738      *             and step is positive, or end date is after this date and step is negative
1739      * @since 9
1740      */
1741     public Stream<LocalDate> datesUntil(LocalDate endExclusive, Period step) {
1742         if (step.isZero()) {
1743             throw new IllegalArgumentException("step is zero");
1744         }
1745         long end = endExclusive.toEpochDay();
1746         long start = toEpochDay();
1747         long until = end - start;
1748         long months = step.toTotalMonths();
1749         long days = step.getDays();
1750         if ((months < 0 && days > 0) || (months > 0 && days < 0)) {
1751             throw new IllegalArgumentException("period months and days are of opposite sign");
1752         }
1753         if (until == 0) {
1754             return Stream.empty();
1755         }
1756         int sign = months > 0 || days > 0 ? 1 : -1;
1757         if (sign < 0 ^ until < 0) {
1758             throw new IllegalArgumentException(endExclusive + (sign < 0 ? " > " : " < ") + this);
1759         }
1760         if (months == 0) {
1761             long steps = (until - sign) / days; // non-negative
1762             return LongStream.rangeClosed(0, steps).mapToObj(
1763                     n -> LocalDate.ofEpochDay(start + n * days));
1764         }
1765         // 48699/1600 = 365.2425/12, no overflow, non-negative result
1766         long steps = until * 1600 / (months * 48699 + days * 1600) + 1;
1767         long addMonths = months * steps;
1768         long addDays = days * steps;
1769         long maxAddMonths = months > 0 ? MAX.getProlepticMonth() - getProlepticMonth()
1770                 : getProlepticMonth() - MIN.getProlepticMonth();
1771         // adjust steps estimation
1772         if (addMonths * sign > maxAddMonths
1773                 || (plusMonths(addMonths).toEpochDay() + addDays) * sign >= end * sign) {
1774             steps--;
1775             addMonths -= months;
1776             addDays -= days;
1777             if (addMonths * sign > maxAddMonths
1778                     || (plusMonths(addMonths).toEpochDay() + addDays) * sign >= end * sign) {
1779                 steps--;
1780             }
1781         }
1782         return LongStream.rangeClosed(0, steps).mapToObj(
1783                 n -> this.plusMonths(months * n).plusDays(days * n));
1784     }
1785 
1786     /**
1787      * Formats this date using the specified formatter.
1788      * <p>
1789      * This date will be passed to the formatter to produce a string.
1790      *
1791      * @param formatter  the formatter to use, not null
1792      * @return the formatted date string, not null
1793      * @throws DateTimeException if an error occurs during printing
1794      */
1795     @Override  // override for Javadoc and performance
1796     public String format(DateTimeFormatter formatter) {
1797         Objects.requireNonNull(formatter, "formatter");
1798         return formatter.format(this);
1799     }
1800 
1801     //-----------------------------------------------------------------------
1802     /**
1803      * Combines this date with a time to create a {@code LocalDateTime}.
1804      * <p>
1805      * This returns a {@code LocalDateTime} formed from this date at the specified time.
1806      * All possible combinations of date and time are valid.
1807      *
1808      * @param time  the time to combine with, not null
1809      * @return the local date-time formed from this date and the specified time, not null
1810      */
1811     @Override
1812     public LocalDateTime atTime(LocalTime time) {
1813         return LocalDateTime.of(this, time);
1814     }
1815 
1816     /**
1817      * Combines this date with a time to create a {@code LocalDateTime}.
1818      * <p>
1819      * This returns a {@code LocalDateTime} formed from this date at the
1820      * specified hour and minute.
1821      * The seconds and nanosecond fields will be set to zero.
1822      * The individual time fields must be within their valid range.
1823      * All possible combinations of date and time are valid.
1824      *
1825      * @param hour  the hour-of-day to use, from 0 to 23
1826      * @param minute  the minute-of-hour to use, from 0 to 59
1827      * @return the local date-time formed from this date and the specified time, not null
1828      * @throws DateTimeException if the value of any field is out of range
1829      */
1830     public LocalDateTime atTime(int hour, int minute) {
1831         return atTime(LocalTime.of(hour, minute));
1832     }
1833 
1834     /**
1835      * Combines this date with a time to create a {@code LocalDateTime}.
1836      * <p>
1837      * This returns a {@code LocalDateTime} formed from this date at the
1838      * specified hour, minute and second.
1839      * The nanosecond field will be set to zero.
1840      * The individual time fields must be within their valid range.
1841      * All possible combinations of date and time are valid.
1842      *
1843      * @param hour  the hour-of-day to use, from 0 to 23
1844      * @param minute  the minute-of-hour to use, from 0 to 59
1845      * @param second  the second-of-minute to represent, from 0 to 59
1846      * @return the local date-time formed from this date and the specified time, not null
1847      * @throws DateTimeException if the value of any field is out of range
1848      */
1849     public LocalDateTime atTime(int hour, int minute, int second) {
1850         return atTime(LocalTime.of(hour, minute, second));
1851     }
1852 
1853     /**
1854      * Combines this date with a time to create a {@code LocalDateTime}.
1855      * <p>
1856      * This returns a {@code LocalDateTime} formed from this date at the
1857      * specified hour, minute, second and nanosecond.
1858      * The individual time fields must be within their valid range.
1859      * All possible combinations of date and time are valid.
1860      *
1861      * @param hour  the hour-of-day to use, from 0 to 23
1862      * @param minute  the minute-of-hour to use, from 0 to 59
1863      * @param second  the second-of-minute to represent, from 0 to 59
1864      * @param nanoOfSecond  the nano-of-second to represent, from 0 to 999,999,999
1865      * @return the local date-time formed from this date and the specified time, not null
1866      * @throws DateTimeException if the value of any field is out of range
1867      */
1868     public LocalDateTime atTime(int hour, int minute, int second, int nanoOfSecond) {
1869         return atTime(LocalTime.of(hour, minute, second, nanoOfSecond));
1870     }
1871 
1872     /**
1873      * Combines this date with an offset time to create an {@code OffsetDateTime}.
1874      * <p>
1875      * This returns an {@code OffsetDateTime} formed from this date at the specified time.
1876      * All possible combinations of date and time are valid.
1877      *
1878      * @param time  the time to combine with, not null
1879      * @return the offset date-time formed from this date and the specified time, not null
1880      */
1881     public OffsetDateTime atTime(OffsetTime time) {
1882         return OffsetDateTime.of(LocalDateTime.of(this, time.toLocalTime()), time.getOffset());
1883     }
1884 
1885     /**
1886      * Combines this date with the time of midnight to create a {@code LocalDateTime}
1887      * at the start of this date.
1888      * <p>
1889      * This returns a {@code LocalDateTime} formed from this date at the time of
1890      * midnight, 00:00, at the start of this date.
1891      *
1892      * @return the local date-time of midnight at the start of this date, not null
1893      */
1894     public LocalDateTime atStartOfDay() {
1895         return LocalDateTime.of(this, LocalTime.MIDNIGHT);
1896     }
1897 
1898     /**
1899      * Returns a zoned date-time from this date at the earliest valid time according
1900      * to the rules in the time-zone.
1901      * <p>
1902      * Time-zone rules, such as daylight savings, mean that not every local date-time
1903      * is valid for the specified zone, thus the local date-time may not be midnight.
1904      * <p>
1905      * In most cases, there is only one valid offset for a local date-time.
1906      * In the case of an overlap, there are two valid offsets, and the earlier one is used,
1907      * corresponding to the first occurrence of midnight on the date.
1908      * In the case of a gap, the zoned date-time will represent the instant just after the gap.
1909      * <p>
1910      * If the zone ID is a {@link ZoneOffset}, then the result always has a time of midnight.
1911      * <p>
1912      * To convert to a specific time in a given time-zone call {@link #atTime(LocalTime)}
1913      * followed by {@link LocalDateTime#atZone(ZoneId)}.
1914      *
1915      * @param zone  the zone ID to use, not null
1916      * @return the zoned date-time formed from this date and the earliest valid time for the zone, not null
1917      */
1918     public ZonedDateTime atStartOfDay(ZoneId zone) {
1919         Objects.requireNonNull(zone, "zone");
1920         // need to handle case where there is a gap from 11:30 to 00:30
1921         // standard ZDT factory would result in 01:00 rather than 00:30
1922         LocalDateTime ldt = atTime(LocalTime.MIDNIGHT);
1923         if (!(zone instanceof ZoneOffset)) {
1924             ZoneRules rules = zone.getRules();
1925             ZoneOffsetTransition trans = rules.getTransition(ldt);
1926             if (trans != null && trans.isGap()) {
1927                 ldt = trans.getDateTimeAfter();
1928             }
1929         }
1930         return ZonedDateTime.of(ldt, zone);
1931     }
1932 
1933     //-----------------------------------------------------------------------
1934     @Override
1935     public long toEpochDay() {
1936         long y = year;
1937         long m = month;
1938         long total = 0;
1939         total += 365 * y;
1940         if (y >= 0) {
1941             total += (y + 3) / 4 - (y + 99) / 100 + (y + 399) / 400;
1942         } else {
1943             total -= y / -4 - y / -100 + y / -400;
1944         }
1945         total += ((367 * m - 362) / 12);
1946         total += day - 1;
1947         if (m > 2) {
1948             total--;
1949             if (isLeapYear() == false) {
1950                 total--;
1951             }
1952         }
1953         return total - DAYS_0000_TO_1970;
1954     }
1955 
1956     /**
1957      * Converts this {@code LocalDate} to the number of seconds since the epoch
1958      * of 1970-01-01T00:00:00Z.
1959      * <p>
1960      * This combines this local date with the specified time and
1961      * offset to calculate the epoch-second value, which is the
1962      * number of elapsed seconds from 1970-01-01T00:00:00Z.
1963      * Instants on the time-line after the epoch are positive, earlier
1964      * are negative.
1965      *
1966      * @param time the local time, not null
1967      * @param offset the zone offset, not null
1968      * @return the number of seconds since the epoch of 1970-01-01T00:00:00Z, may be negative
1969      * @since 9
1970      */
1971     public long toEpochSecond(LocalTime time, ZoneOffset offset) {
1972         Objects.requireNonNull(time, "time");
1973         Objects.requireNonNull(offset, "offset");
1974         long secs = toEpochDay() * SECONDS_PER_DAY + time.toSecondOfDay();
1975         secs -= offset.getTotalSeconds();
1976         return secs;
1977     }
1978 
1979     //-----------------------------------------------------------------------
1980     /**
1981      * Compares this date to another date.
1982      * <p>
1983      * The comparison is primarily based on the date, from earliest to latest.
1984      * It is "consistent with equals", as defined by {@link Comparable}.
1985      * <p>
1986      * If all the dates being compared are instances of {@code LocalDate},
1987      * then the comparison will be entirely based on the date.
1988      * If some dates being compared are in different chronologies, then the
1989      * chronology is also considered, see {@link java.time.chrono.ChronoLocalDate#compareTo}.
1990      *
1991      * @param other  the other date to compare to, not null
1992      * @return the comparator value, that is the comparison of this local date with
1993      *          the {@code other} local date and this chronology with the {@code other} chronology,
1994      *          in order, returning the first non-zero result, and otherwise returning zero
1995      * @see #isBefore
1996      * @see #isAfter
1997      */
1998     @Override  // override for Javadoc and performance
1999     public int compareTo(ChronoLocalDate other) {
2000         if (other instanceof LocalDate) {
2001             return compareTo0((LocalDate) other);
2002         }
2003         return ChronoLocalDate.super.compareTo(other);
2004     }
2005 
2006     int compareTo0(LocalDate otherDate) {
2007         int cmp = (year - otherDate.year);
2008         if (cmp == 0) {
2009             cmp = (month - otherDate.month);
2010             if (cmp == 0) {
2011                 cmp = (day - otherDate.day);
2012             }
2013         }
2014         return cmp;
2015     }
2016 
2017     /**
2018      * Checks if this date is after the specified date.
2019      * <p>
2020      * This checks to see if this date represents a point on the
2021      * local time-line after the other date.
2022      * <pre>
2023      *   LocalDate a = LocalDate.of(2012, 6, 30);
2024      *   LocalDate b = LocalDate.of(2012, 7, 1);
2025      *   a.isAfter(b) == false
2026      *   a.isAfter(a) == false
2027      *   b.isAfter(a) == true
2028      * </pre>
2029      * <p>
2030      * This method only considers the position of the two dates on the local time-line.
2031      * It does not take into account the chronology, or calendar system.
2032      * This is different from the comparison in {@link #compareTo(ChronoLocalDate)},
2033      * but is the same approach as {@link ChronoLocalDate#timeLineOrder()}.
2034      *
2035      * @param other  the other date to compare to, not null
2036      * @return true if this date is after the specified date
2037      */
2038     @Override  // override for Javadoc and performance
2039     public boolean isAfter(ChronoLocalDate other) {
2040         if (other instanceof LocalDate) {
2041             return compareTo0((LocalDate) other) > 0;
2042         }
2043         return ChronoLocalDate.super.isAfter(other);
2044     }
2045 
2046     /**
2047      * Checks if this date is before the specified date.
2048      * <p>
2049      * This checks to see if this date represents a point on the
2050      * local time-line before the other date.
2051      * <pre>
2052      *   LocalDate a = LocalDate.of(2012, 6, 30);
2053      *   LocalDate b = LocalDate.of(2012, 7, 1);
2054      *   a.isBefore(b) == true
2055      *   a.isBefore(a) == false
2056      *   b.isBefore(a) == false
2057      * </pre>
2058      * <p>
2059      * This method only considers the position of the two dates on the local time-line.
2060      * It does not take into account the chronology, or calendar system.
2061      * This is different from the comparison in {@link #compareTo(ChronoLocalDate)},
2062      * but is the same approach as {@link ChronoLocalDate#timeLineOrder()}.
2063      *
2064      * @param other  the other date to compare to, not null
2065      * @return true if this date is before the specified date
2066      */
2067     @Override  // override for Javadoc and performance
2068     public boolean isBefore(ChronoLocalDate other) {
2069         if (other instanceof LocalDate) {
2070             return compareTo0((LocalDate) other) < 0;
2071         }
2072         return ChronoLocalDate.super.isBefore(other);
2073     }
2074 
2075     /**
2076      * Checks if this date is equal to the specified date.
2077      * <p>
2078      * This checks to see if this date represents the same point on the
2079      * local time-line as the other date.
2080      * <pre>
2081      *   LocalDate a = LocalDate.of(2012, 6, 30);
2082      *   LocalDate b = LocalDate.of(2012, 7, 1);
2083      *   a.isEqual(b) == false
2084      *   a.isEqual(a) == true
2085      *   b.isEqual(a) == false
2086      * </pre>
2087      * <p>
2088      * This method only considers the position of the two dates on the local time-line.
2089      * It does not take into account the chronology, or calendar system.
2090      * This is different from the comparison in {@link #compareTo(ChronoLocalDate)}
2091      * but is the same approach as {@link ChronoLocalDate#timeLineOrder()}.
2092      *
2093      * @param other  the other date to compare to, not null
2094      * @return true if this date is equal to the specified date
2095      */
2096     @Override  // override for Javadoc and performance
2097     public boolean isEqual(ChronoLocalDate other) {
2098         if (other instanceof LocalDate) {
2099             return compareTo0((LocalDate) other) == 0;
2100         }
2101         return ChronoLocalDate.super.isEqual(other);
2102     }
2103 
2104     //-----------------------------------------------------------------------
2105     /**
2106      * Checks if this date is equal to another date.
2107      * <p>
2108      * Compares this {@code LocalDate} with another ensuring that the date is the same.
2109      * <p>
2110      * Only objects of type {@code LocalDate} are compared, other types return false.
2111      * To compare the dates of two {@code TemporalAccessor} instances, including dates
2112      * in two different chronologies, use {@link ChronoField#EPOCH_DAY} as a comparator.
2113      *
2114      * @param obj  the object to check, null returns false
2115      * @return true if this is equal to the other date
2116      */
2117     @Override
2118     public boolean equals(Object obj) {
2119         if (this == obj) {
2120             return true;
2121         }
2122         if (obj instanceof LocalDate) {
2123             return compareTo0((LocalDate) obj) == 0;
2124         }
2125         return false;
2126     }
2127 
2128     /**
2129      * A hash code for this date.
2130      *
2131      * @return a suitable hash code
2132      */
2133     @Override
2134     public int hashCode() {
2135         int yearValue = year;
2136         int monthValue = month;
2137         int dayValue = day;
2138         return (yearValue & 0xFFFFF800) ^ ((yearValue << 11) + (monthValue << 6) + (dayValue));
2139     }
2140 
2141     //-----------------------------------------------------------------------
2142     /**
2143      * Outputs this date as a {@code String}, such as {@code 2007-12-03}.
2144      * <p>
2145      * The output will be in the ISO-8601 format {@code uuuu-MM-dd}.
2146      *
2147      * @return a string representation of this date, not null
2148      */
2149     @Override
2150     public String toString() {
2151         int yearValue = year;
2152         int monthValue = month;
2153         int dayValue = day;
2154         int absYear = Math.abs(yearValue);
2155         StringBuilder buf = new StringBuilder(10);
2156         if (absYear < 1000) {
2157             if (yearValue < 0) {
2158                 buf.append(yearValue - 10000).deleteCharAt(1);
2159             } else {
2160                 buf.append(yearValue + 10000).deleteCharAt(0);
2161             }
2162         } else {
2163             if (yearValue > 9999) {
2164                 buf.append('+');
2165             }
2166             buf.append(yearValue);
2167         }
2168         return buf.append(monthValue < 10 ? "-0" : "-")
2169             .append(monthValue)
2170             .append(dayValue < 10 ? "-0" : "-")
2171             .append(dayValue)
2172             .toString();
2173     }
2174 
2175     //-----------------------------------------------------------------------
2176     /**
2177      * Writes the object using a
2178      * <a href="{@docRoot}/serialized-form.html#java.time.Ser">dedicated serialized form</a>.
2179      * @serialData
2180      * <pre>
2181      *  out.writeByte(3);  // identifies a LocalDate
2182      *  out.writeInt(year);
2183      *  out.writeByte(month);
2184      *  out.writeByte(day);
2185      * </pre>
2186      *
2187      * @return the instance of {@code Ser}, not null
2188      */
2189     @java.io.Serial
2190     private Object writeReplace() {
2191         return new Ser(Ser.LOCAL_DATE_TYPE, this);
2192     }
2193 
2194     /**
2195      * Defend against malicious streams.
2196      *
2197      * @param s the stream to read
2198      * @throws InvalidObjectException always
2199      */
2200     @java.io.Serial
2201     private void readObject(ObjectInputStream s) throws InvalidObjectException {
2202         throw new InvalidObjectException("Deserialization via serialization delegate");
2203     }
2204 
2205     void writeExternal(DataOutput out) throws IOException {
2206         out.writeInt(year);
2207         out.writeByte(month);
2208         out.writeByte(day);
2209     }
2210 
2211     static LocalDate readExternal(DataInput in) throws IOException {
2212         int year = in.readInt();
2213         int month = in.readByte();
2214         int dayOfMonth = in.readByte();
2215         return LocalDate.of(year, month, dayOfMonth);
2216     }
2217 
2218 }