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