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