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