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