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