Path: blob/aarch64-shenandoah-jdk8u272-b10/jdk/src/share/classes/java/time/LocalDate.java
38829 views
/*1* Copyright (c) 2012, 2015, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/2425/*26* This file is available under and governed by the GNU General Public27* License version 2 only, as published by the Free Software Foundation.28* However, the following notice accompanied the original version of this29* file:30*31* Copyright (c) 2007-2012, Stephen Colebourne & Michael Nascimento Santos32*33* All rights reserved.34*35* Redistribution and use in source and binary forms, with or without36* modification, are permitted provided that the following conditions are met:37*38* * Redistributions of source code must retain the above copyright notice,39* this list of conditions and the following disclaimer.40*41* * Redistributions in binary form must reproduce the above copyright notice,42* this list of conditions and the following disclaimer in the documentation43* and/or other materials provided with the distribution.44*45* * Neither the name of JSR-310 nor the names of its contributors46* may be used to endorse or promote products derived from this software47* without specific prior written permission.48*49* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS50* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT51* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR52* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR53* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,54* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,55* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR56* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF57* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING58* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS59* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.60*/61package java.time;6263import static java.time.LocalTime.SECONDS_PER_DAY;64import static java.time.temporal.ChronoField.ALIGNED_DAY_OF_WEEK_IN_MONTH;65import static java.time.temporal.ChronoField.ALIGNED_DAY_OF_WEEK_IN_YEAR;66import static java.time.temporal.ChronoField.ALIGNED_WEEK_OF_MONTH;67import static java.time.temporal.ChronoField.ALIGNED_WEEK_OF_YEAR;68import static java.time.temporal.ChronoField.DAY_OF_MONTH;69import static java.time.temporal.ChronoField.DAY_OF_YEAR;70import static java.time.temporal.ChronoField.EPOCH_DAY;71import static java.time.temporal.ChronoField.ERA;72import static java.time.temporal.ChronoField.MONTH_OF_YEAR;73import static java.time.temporal.ChronoField.PROLEPTIC_MONTH;74import static java.time.temporal.ChronoField.YEAR;7576import java.io.DataInput;77import java.io.DataOutput;78import java.io.IOException;79import java.io.InvalidObjectException;80import java.io.ObjectInputStream;81import java.io.Serializable;82import java.time.chrono.ChronoLocalDate;83import java.time.chrono.Era;84import java.time.chrono.IsoChronology;85import java.time.format.DateTimeFormatter;86import java.time.format.DateTimeParseException;87import java.time.temporal.ChronoField;88import java.time.temporal.ChronoUnit;89import java.time.temporal.Temporal;90import java.time.temporal.TemporalAccessor;91import java.time.temporal.TemporalAdjuster;92import java.time.temporal.TemporalAmount;93import java.time.temporal.TemporalField;94import java.time.temporal.TemporalQueries;95import java.time.temporal.TemporalQuery;96import java.time.temporal.TemporalUnit;97import java.time.temporal.UnsupportedTemporalTypeException;98import java.time.temporal.ValueRange;99import java.time.zone.ZoneOffsetTransition;100import java.time.zone.ZoneRules;101import java.util.Objects;102103/**104* A date without a time-zone in the ISO-8601 calendar system,105* such as {@code 2007-12-03}.106* <p>107* {@code LocalDate} is an immutable date-time object that represents a date,108* often viewed as year-month-day. Other date fields, such as day-of-year,109* day-of-week and week-of-year, can also be accessed.110* For example, the value "2nd October 2007" can be stored in a {@code LocalDate}.111* <p>112* This class does not store or represent a time or time-zone.113* Instead, it is a description of the date, as used for birthdays.114* It cannot represent an instant on the time-line without additional information115* such as an offset or time-zone.116* <p>117* The ISO-8601 calendar system is the modern civil calendar system used today118* in most of the world. It is equivalent to the proleptic Gregorian calendar119* system, in which today's rules for leap years are applied for all time.120* For most applications written today, the ISO-8601 rules are entirely suitable.121* However, any application that makes use of historical dates, and requires them122* to be accurate will find the ISO-8601 approach unsuitable.123*124* <p>125* This is a <a href="{@docRoot}/java/lang/doc-files/ValueBased.html">value-based</a>126* class; use of identity-sensitive operations (including reference equality127* ({@code ==}), identity hash code, or synchronization) on instances of128* {@code LocalDate} may have unpredictable results and should be avoided.129* The {@code equals} method should be used for comparisons.130*131* @implSpec132* This class is immutable and thread-safe.133*134* @since 1.8135*/136public final class LocalDate137implements Temporal, TemporalAdjuster, ChronoLocalDate, Serializable {138139/**140* The minimum supported {@code LocalDate}, '-999999999-01-01'.141* This could be used by an application as a "far past" date.142*/143public static final LocalDate MIN = LocalDate.of(Year.MIN_VALUE, 1, 1);144/**145* The maximum supported {@code LocalDate}, '+999999999-12-31'.146* This could be used by an application as a "far future" date.147*/148public static final LocalDate MAX = LocalDate.of(Year.MAX_VALUE, 12, 31);149150/**151* Serialization version.152*/153private static final long serialVersionUID = 2942565459149668126L;154/**155* The number of days in a 400 year cycle.156*/157private static final int DAYS_PER_CYCLE = 146097;158/**159* The number of days from year zero to year 1970.160* There are five 400 year cycles from year zero to 2000.161* There are 7 leap years from 1970 to 2000.162*/163static final long DAYS_0000_TO_1970 = (DAYS_PER_CYCLE * 5L) - (30L * 365L + 7L);164165/**166* The year.167*/168private final int year;169/**170* The month-of-year.171*/172private final short month;173/**174* The day-of-month.175*/176private final short day;177178//-----------------------------------------------------------------------179/**180* Obtains the current date from the system clock in the default time-zone.181* <p>182* This will query the {@link Clock#systemDefaultZone() system clock} in the default183* time-zone to obtain the current date.184* <p>185* Using this method will prevent the ability to use an alternate clock for testing186* because the clock is hard-coded.187*188* @return the current date using the system clock and default time-zone, not null189*/190public static LocalDate now() {191return now(Clock.systemDefaultZone());192}193194/**195* Obtains the current date from the system clock in the specified time-zone.196* <p>197* This will query the {@link Clock#system(ZoneId) system clock} to obtain the current date.198* Specifying the time-zone avoids dependence on the default time-zone.199* <p>200* Using this method will prevent the ability to use an alternate clock for testing201* because the clock is hard-coded.202*203* @param zone the zone ID to use, not null204* @return the current date using the system clock, not null205*/206public static LocalDate now(ZoneId zone) {207return now(Clock.system(zone));208}209210/**211* Obtains the current date from the specified clock.212* <p>213* This will query the specified clock to obtain the current date - today.214* Using this method allows the use of an alternate clock for testing.215* The alternate clock may be introduced using {@link Clock dependency injection}.216*217* @param clock the clock to use, not null218* @return the current date, not null219*/220public static LocalDate now(Clock clock) {221Objects.requireNonNull(clock, "clock");222// inline to avoid creating object and Instant checks223final Instant now = clock.instant(); // called once224ZoneOffset offset = clock.getZone().getRules().getOffset(now);225long epochSec = now.getEpochSecond() + offset.getTotalSeconds(); // overflow caught later226long epochDay = Math.floorDiv(epochSec, SECONDS_PER_DAY);227return LocalDate.ofEpochDay(epochDay);228}229230//-----------------------------------------------------------------------231/**232* Obtains an instance of {@code LocalDate} from a year, month and day.233* <p>234* This returns a {@code LocalDate} with the specified year, month and day-of-month.235* The day must be valid for the year and month, otherwise an exception will be thrown.236*237* @param year the year to represent, from MIN_YEAR to MAX_YEAR238* @param month the month-of-year to represent, not null239* @param dayOfMonth the day-of-month to represent, from 1 to 31240* @return the local date, not null241* @throws DateTimeException if the value of any field is out of range,242* or if the day-of-month is invalid for the month-year243*/244public static LocalDate of(int year, Month month, int dayOfMonth) {245YEAR.checkValidValue(year);246Objects.requireNonNull(month, "month");247DAY_OF_MONTH.checkValidValue(dayOfMonth);248return create(year, month.getValue(), dayOfMonth);249}250251/**252* Obtains an instance of {@code LocalDate} from a year, month and day.253* <p>254* This returns a {@code LocalDate} with the specified year, month and day-of-month.255* The day must be valid for the year and month, otherwise an exception will be thrown.256*257* @param year the year to represent, from MIN_YEAR to MAX_YEAR258* @param month the month-of-year to represent, from 1 (January) to 12 (December)259* @param dayOfMonth the day-of-month to represent, from 1 to 31260* @return the local date, not null261* @throws DateTimeException if the value of any field is out of range,262* or if the day-of-month is invalid for the month-year263*/264public static LocalDate of(int year, int month, int dayOfMonth) {265YEAR.checkValidValue(year);266MONTH_OF_YEAR.checkValidValue(month);267DAY_OF_MONTH.checkValidValue(dayOfMonth);268return create(year, month, dayOfMonth);269}270271//-----------------------------------------------------------------------272/**273* Obtains an instance of {@code LocalDate} from a year and day-of-year.274* <p>275* This returns a {@code LocalDate} with the specified year and day-of-year.276* The day-of-year must be valid for the year, otherwise an exception will be thrown.277*278* @param year the year to represent, from MIN_YEAR to MAX_YEAR279* @param dayOfYear the day-of-year to represent, from 1 to 366280* @return the local date, not null281* @throws DateTimeException if the value of any field is out of range,282* or if the day-of-year is invalid for the year283*/284public static LocalDate ofYearDay(int year, int dayOfYear) {285YEAR.checkValidValue(year);286DAY_OF_YEAR.checkValidValue(dayOfYear);287boolean leap = IsoChronology.INSTANCE.isLeapYear(year);288if (dayOfYear == 366 && leap == false) {289throw new DateTimeException("Invalid date 'DayOfYear 366' as '" + year + "' is not a leap year");290}291Month moy = Month.of((dayOfYear - 1) / 31 + 1);292int monthEnd = moy.firstDayOfYear(leap) + moy.length(leap) - 1;293if (dayOfYear > monthEnd) {294moy = moy.plus(1);295}296int dom = dayOfYear - moy.firstDayOfYear(leap) + 1;297return new LocalDate(year, moy.getValue(), dom);298}299300//-----------------------------------------------------------------------301/**302* Obtains an instance of {@code LocalDate} from the epoch day count.303* <p>304* This returns a {@code LocalDate} with the specified epoch-day.305* The {@link ChronoField#EPOCH_DAY EPOCH_DAY} is a simple incrementing count306* of days where day 0 is 1970-01-01. Negative numbers represent earlier days.307*308* @param epochDay the Epoch Day to convert, based on the epoch 1970-01-01309* @return the local date, not null310* @throws DateTimeException if the epoch day exceeds the supported date range311*/312public static LocalDate ofEpochDay(long epochDay) {313long zeroDay = epochDay + DAYS_0000_TO_1970;314// find the march-based year315zeroDay -= 60; // adjust to 0000-03-01 so leap day is at end of four year cycle316long adjust = 0;317if (zeroDay < 0) {318// adjust negative years to positive for calculation319long adjustCycles = (zeroDay + 1) / DAYS_PER_CYCLE - 1;320adjust = adjustCycles * 400;321zeroDay += -adjustCycles * DAYS_PER_CYCLE;322}323long yearEst = (400 * zeroDay + 591) / DAYS_PER_CYCLE;324long doyEst = zeroDay - (365 * yearEst + yearEst / 4 - yearEst / 100 + yearEst / 400);325if (doyEst < 0) {326// fix estimate327yearEst--;328doyEst = zeroDay - (365 * yearEst + yearEst / 4 - yearEst / 100 + yearEst / 400);329}330yearEst += adjust; // reset any negative year331int marchDoy0 = (int) doyEst;332333// convert march-based values back to january-based334int marchMonth0 = (marchDoy0 * 5 + 2) / 153;335int month = (marchMonth0 + 2) % 12 + 1;336int dom = marchDoy0 - (marchMonth0 * 306 + 5) / 10 + 1;337yearEst += marchMonth0 / 10;338339// check year now we are certain it is correct340int year = YEAR.checkValidIntValue(yearEst);341return new LocalDate(year, month, dom);342}343344//-----------------------------------------------------------------------345/**346* Obtains an instance of {@code LocalDate} from a temporal object.347* <p>348* This obtains a local date based on the specified temporal.349* A {@code TemporalAccessor} represents an arbitrary set of date and time information,350* which this factory converts to an instance of {@code LocalDate}.351* <p>352* The conversion uses the {@link TemporalQueries#localDate()} query, which relies353* on extracting the {@link ChronoField#EPOCH_DAY EPOCH_DAY} field.354* <p>355* This method matches the signature of the functional interface {@link TemporalQuery}356* allowing it to be used as a query via method reference, {@code LocalDate::from}.357*358* @param temporal the temporal object to convert, not null359* @return the local date, not null360* @throws DateTimeException if unable to convert to a {@code LocalDate}361*/362public static LocalDate from(TemporalAccessor temporal) {363Objects.requireNonNull(temporal, "temporal");364LocalDate date = temporal.query(TemporalQueries.localDate());365if (date == null) {366throw new DateTimeException("Unable to obtain LocalDate from TemporalAccessor: " +367temporal + " of type " + temporal.getClass().getName());368}369return date;370}371372//-----------------------------------------------------------------------373/**374* Obtains an instance of {@code LocalDate} from a text string such as {@code 2007-12-03}.375* <p>376* The string must represent a valid date and is parsed using377* {@link java.time.format.DateTimeFormatter#ISO_LOCAL_DATE}.378*379* @param text the text to parse such as "2007-12-03", not null380* @return the parsed local date, not null381* @throws DateTimeParseException if the text cannot be parsed382*/383public static LocalDate parse(CharSequence text) {384return parse(text, DateTimeFormatter.ISO_LOCAL_DATE);385}386387/**388* Obtains an instance of {@code LocalDate} from a text string using a specific formatter.389* <p>390* The text is parsed using the formatter, returning a date.391*392* @param text the text to parse, not null393* @param formatter the formatter to use, not null394* @return the parsed local date, not null395* @throws DateTimeParseException if the text cannot be parsed396*/397public static LocalDate parse(CharSequence text, DateTimeFormatter formatter) {398Objects.requireNonNull(formatter, "formatter");399return formatter.parse(text, LocalDate::from);400}401402//-----------------------------------------------------------------------403/**404* Creates a local date from the year, month and day fields.405*406* @param year the year to represent, validated from MIN_YEAR to MAX_YEAR407* @param month the month-of-year to represent, from 1 to 12, validated408* @param dayOfMonth the day-of-month to represent, validated from 1 to 31409* @return the local date, not null410* @throws DateTimeException if the day-of-month is invalid for the month-year411*/412private static LocalDate create(int year, int month, int dayOfMonth) {413if (dayOfMonth > 28) {414int dom = 31;415switch (month) {416case 2:417dom = (IsoChronology.INSTANCE.isLeapYear(year) ? 29 : 28);418break;419case 4:420case 6:421case 9:422case 11:423dom = 30;424break;425}426if (dayOfMonth > dom) {427if (dayOfMonth == 29) {428throw new DateTimeException("Invalid date 'February 29' as '" + year + "' is not a leap year");429} else {430throw new DateTimeException("Invalid date '" + Month.of(month).name() + " " + dayOfMonth + "'");431}432}433}434return new LocalDate(year, month, dayOfMonth);435}436437/**438* Resolves the date, resolving days past the end of month.439*440* @param year the year to represent, validated from MIN_YEAR to MAX_YEAR441* @param month the month-of-year to represent, validated from 1 to 12442* @param day the day-of-month to represent, validated from 1 to 31443* @return the resolved date, not null444*/445private static LocalDate resolvePreviousValid(int year, int month, int day) {446switch (month) {447case 2:448day = Math.min(day, IsoChronology.INSTANCE.isLeapYear(year) ? 29 : 28);449break;450case 4:451case 6:452case 9:453case 11:454day = Math.min(day, 30);455break;456}457return new LocalDate(year, month, day);458}459460/**461* Constructor, previously validated.462*463* @param year the year to represent, from MIN_YEAR to MAX_YEAR464* @param month the month-of-year to represent, not null465* @param dayOfMonth the day-of-month to represent, valid for year-month, from 1 to 31466*/467private LocalDate(int year, int month, int dayOfMonth) {468this.year = year;469this.month = (short) month;470this.day = (short) dayOfMonth;471}472473//-----------------------------------------------------------------------474/**475* Checks if the specified field is supported.476* <p>477* This checks if this date can be queried for the specified field.478* If false, then calling the {@link #range(TemporalField) range},479* {@link #get(TemporalField) get} and {@link #with(TemporalField, long)}480* methods will throw an exception.481* <p>482* If the field is a {@link ChronoField} then the query is implemented here.483* The supported fields are:484* <ul>485* <li>{@code DAY_OF_WEEK}486* <li>{@code ALIGNED_DAY_OF_WEEK_IN_MONTH}487* <li>{@code ALIGNED_DAY_OF_WEEK_IN_YEAR}488* <li>{@code DAY_OF_MONTH}489* <li>{@code DAY_OF_YEAR}490* <li>{@code EPOCH_DAY}491* <li>{@code ALIGNED_WEEK_OF_MONTH}492* <li>{@code ALIGNED_WEEK_OF_YEAR}493* <li>{@code MONTH_OF_YEAR}494* <li>{@code PROLEPTIC_MONTH}495* <li>{@code YEAR_OF_ERA}496* <li>{@code YEAR}497* <li>{@code ERA}498* </ul>499* All other {@code ChronoField} instances will return false.500* <p>501* If the field is not a {@code ChronoField}, then the result of this method502* is obtained by invoking {@code TemporalField.isSupportedBy(TemporalAccessor)}503* passing {@code this} as the argument.504* Whether the field is supported is determined by the field.505*506* @param field the field to check, null returns false507* @return true if the field is supported on this date, false if not508*/509@Override // override for Javadoc510public boolean isSupported(TemporalField field) {511return ChronoLocalDate.super.isSupported(field);512}513514/**515* Checks if the specified unit is supported.516* <p>517* This checks if the specified unit can be added to, or subtracted from, this date.518* If false, then calling the {@link #plus(long, TemporalUnit)} and519* {@link #minus(long, TemporalUnit) minus} methods will throw an exception.520* <p>521* If the unit is a {@link ChronoUnit} then the query is implemented here.522* The supported units are:523* <ul>524* <li>{@code DAYS}525* <li>{@code WEEKS}526* <li>{@code MONTHS}527* <li>{@code YEARS}528* <li>{@code DECADES}529* <li>{@code CENTURIES}530* <li>{@code MILLENNIA}531* <li>{@code ERAS}532* </ul>533* All other {@code ChronoUnit} instances will return false.534* <p>535* If the unit is not a {@code ChronoUnit}, then the result of this method536* is obtained by invoking {@code TemporalUnit.isSupportedBy(Temporal)}537* passing {@code this} as the argument.538* Whether the unit is supported is determined by the unit.539*540* @param unit the unit to check, null returns false541* @return true if the unit can be added/subtracted, false if not542*/543@Override // override for Javadoc544public boolean isSupported(TemporalUnit unit) {545return ChronoLocalDate.super.isSupported(unit);546}547548//-----------------------------------------------------------------------549/**550* Gets the range of valid values for the specified field.551* <p>552* The range object expresses the minimum and maximum valid values for a field.553* This date is used to enhance the accuracy of the returned range.554* If it is not possible to return the range, because the field is not supported555* or for some other reason, an exception is thrown.556* <p>557* If the field is a {@link ChronoField} then the query is implemented here.558* The {@link #isSupported(TemporalField) supported fields} will return559* appropriate range instances.560* All other {@code ChronoField} instances will throw an {@code UnsupportedTemporalTypeException}.561* <p>562* If the field is not a {@code ChronoField}, then the result of this method563* is obtained by invoking {@code TemporalField.rangeRefinedBy(TemporalAccessor)}564* passing {@code this} as the argument.565* Whether the range can be obtained is determined by the field.566*567* @param field the field to query the range for, not null568* @return the range of valid values for the field, not null569* @throws DateTimeException if the range for the field cannot be obtained570* @throws UnsupportedTemporalTypeException if the field is not supported571*/572@Override573public ValueRange range(TemporalField field) {574if (field instanceof ChronoField) {575ChronoField f = (ChronoField) field;576if (f.isDateBased()) {577switch (f) {578case DAY_OF_MONTH: return ValueRange.of(1, lengthOfMonth());579case DAY_OF_YEAR: return ValueRange.of(1, lengthOfYear());580case ALIGNED_WEEK_OF_MONTH: return ValueRange.of(1, getMonth() == Month.FEBRUARY && isLeapYear() == false ? 4 : 5);581case YEAR_OF_ERA:582return (getYear() <= 0 ? ValueRange.of(1, Year.MAX_VALUE + 1) : ValueRange.of(1, Year.MAX_VALUE));583}584return field.range();585}586throw new UnsupportedTemporalTypeException("Unsupported field: " + field);587}588return field.rangeRefinedBy(this);589}590591/**592* Gets the value of the specified field from this date as an {@code int}.593* <p>594* This queries this date for the value of the specified field.595* The returned value will always be within the valid range of values for the field.596* If it is not possible to return the value, because the field is not supported597* or for some other reason, an exception is thrown.598* <p>599* If the field is a {@link ChronoField} then the query is implemented here.600* The {@link #isSupported(TemporalField) supported fields} will return valid601* values based on this date, except {@code EPOCH_DAY} and {@code PROLEPTIC_MONTH}602* which are too large to fit in an {@code int} and throw a {@code DateTimeException}.603* All other {@code ChronoField} instances will throw an {@code UnsupportedTemporalTypeException}.604* <p>605* If the field is not a {@code ChronoField}, then the result of this method606* is obtained by invoking {@code TemporalField.getFrom(TemporalAccessor)}607* passing {@code this} as the argument. Whether the value can be obtained,608* and what the value represents, is determined by the field.609*610* @param field the field to get, not null611* @return the value for the field612* @throws DateTimeException if a value for the field cannot be obtained or613* the value is outside the range of valid values for the field614* @throws UnsupportedTemporalTypeException if the field is not supported or615* the range of values exceeds an {@code int}616* @throws ArithmeticException if numeric overflow occurs617*/618@Override // override for Javadoc and performance619public int get(TemporalField field) {620if (field instanceof ChronoField) {621return get0(field);622}623return ChronoLocalDate.super.get(field);624}625626/**627* Gets the value of the specified field from this date as a {@code long}.628* <p>629* This queries this date for the value of the specified field.630* If it is not possible to return the value, because the field is not supported631* or for some other reason, an exception is thrown.632* <p>633* If the field is a {@link ChronoField} then the query is implemented here.634* The {@link #isSupported(TemporalField) supported fields} will return valid635* values based on this date.636* All other {@code ChronoField} instances will throw an {@code UnsupportedTemporalTypeException}.637* <p>638* If the field is not a {@code ChronoField}, then the result of this method639* is obtained by invoking {@code TemporalField.getFrom(TemporalAccessor)}640* passing {@code this} as the argument. Whether the value can be obtained,641* and what the value represents, is determined by the field.642*643* @param field the field to get, not null644* @return the value for the field645* @throws DateTimeException if a value for the field cannot be obtained646* @throws UnsupportedTemporalTypeException if the field is not supported647* @throws ArithmeticException if numeric overflow occurs648*/649@Override650public long getLong(TemporalField field) {651if (field instanceof ChronoField) {652if (field == EPOCH_DAY) {653return toEpochDay();654}655if (field == PROLEPTIC_MONTH) {656return getProlepticMonth();657}658return get0(field);659}660return field.getFrom(this);661}662663private int get0(TemporalField field) {664switch ((ChronoField) field) {665case DAY_OF_WEEK: return getDayOfWeek().getValue();666case ALIGNED_DAY_OF_WEEK_IN_MONTH: return ((day - 1) % 7) + 1;667case ALIGNED_DAY_OF_WEEK_IN_YEAR: return ((getDayOfYear() - 1) % 7) + 1;668case DAY_OF_MONTH: return day;669case DAY_OF_YEAR: return getDayOfYear();670case EPOCH_DAY: throw new UnsupportedTemporalTypeException("Invalid field 'EpochDay' for get() method, use getLong() instead");671case ALIGNED_WEEK_OF_MONTH: return ((day - 1) / 7) + 1;672case ALIGNED_WEEK_OF_YEAR: return ((getDayOfYear() - 1) / 7) + 1;673case MONTH_OF_YEAR: return month;674case PROLEPTIC_MONTH: throw new UnsupportedTemporalTypeException("Invalid field 'ProlepticMonth' for get() method, use getLong() instead");675case YEAR_OF_ERA: return (year >= 1 ? year : 1 - year);676case YEAR: return year;677case ERA: return (year >= 1 ? 1 : 0);678}679throw new UnsupportedTemporalTypeException("Unsupported field: " + field);680}681682private long getProlepticMonth() {683return (year * 12L + month - 1);684}685686//-----------------------------------------------------------------------687/**688* Gets the chronology of this date, which is the ISO calendar system.689* <p>690* The {@code Chronology} represents the calendar system in use.691* The ISO-8601 calendar system is the modern civil calendar system used today692* in most of the world. It is equivalent to the proleptic Gregorian calendar693* system, in which today's rules for leap years are applied for all time.694*695* @return the ISO chronology, not null696*/697@Override698public IsoChronology getChronology() {699return IsoChronology.INSTANCE;700}701702/**703* Gets the era applicable at this date.704* <p>705* The official ISO-8601 standard does not define eras, however {@code IsoChronology} does.706* It defines two eras, 'CE' from year one onwards and 'BCE' from year zero backwards.707* Since dates before the Julian-Gregorian cutover are not in line with history,708* the cutover between 'BCE' and 'CE' is also not aligned with the commonly used709* eras, often referred to using 'BC' and 'AD'.710* <p>711* Users of this class should typically ignore this method as it exists primarily712* to fulfill the {@link ChronoLocalDate} contract where it is necessary to support713* the Japanese calendar system.714* <p>715* The returned era will be a singleton capable of being compared with the constants716* in {@link IsoChronology} using the {@code ==} operator.717*718* @return the {@code IsoChronology} era constant applicable at this date, not null719*/720@Override // override for Javadoc721public Era getEra() {722return ChronoLocalDate.super.getEra();723}724725/**726* Gets the year field.727* <p>728* This method returns the primitive {@code int} value for the year.729* <p>730* The year returned by this method is proleptic as per {@code get(YEAR)}.731* To obtain the year-of-era, use {@code get(YEAR_OF_ERA)}.732*733* @return the year, from MIN_YEAR to MAX_YEAR734*/735public int getYear() {736return year;737}738739/**740* Gets the month-of-year field from 1 to 12.741* <p>742* This method returns the month as an {@code int} from 1 to 12.743* Application code is frequently clearer if the enum {@link Month}744* is used by calling {@link #getMonth()}.745*746* @return the month-of-year, from 1 to 12747* @see #getMonth()748*/749public int getMonthValue() {750return month;751}752753/**754* Gets the month-of-year field using the {@code Month} enum.755* <p>756* This method returns the enum {@link Month} for the month.757* This avoids confusion as to what {@code int} values mean.758* If you need access to the primitive {@code int} value then the enum759* provides the {@link Month#getValue() int value}.760*761* @return the month-of-year, not null762* @see #getMonthValue()763*/764public Month getMonth() {765return Month.of(month);766}767768/**769* Gets the day-of-month field.770* <p>771* This method returns the primitive {@code int} value for the day-of-month.772*773* @return the day-of-month, from 1 to 31774*/775public int getDayOfMonth() {776return day;777}778779/**780* Gets the day-of-year field.781* <p>782* This method returns the primitive {@code int} value for the day-of-year.783*784* @return the day-of-year, from 1 to 365, or 366 in a leap year785*/786public int getDayOfYear() {787return getMonth().firstDayOfYear(isLeapYear()) + day - 1;788}789790/**791* Gets the day-of-week field, which is an enum {@code DayOfWeek}.792* <p>793* This method returns the enum {@link DayOfWeek} for the day-of-week.794* This avoids confusion as to what {@code int} values mean.795* If you need access to the primitive {@code int} value then the enum796* provides the {@link DayOfWeek#getValue() int value}.797* <p>798* Additional information can be obtained from the {@code DayOfWeek}.799* This includes textual names of the values.800*801* @return the day-of-week, not null802*/803public DayOfWeek getDayOfWeek() {804int dow0 = (int)Math.floorMod(toEpochDay() + 3, 7);805return DayOfWeek.of(dow0 + 1);806}807808//-----------------------------------------------------------------------809/**810* Checks if the year is a leap year, according to the ISO proleptic811* calendar system rules.812* <p>813* This method applies the current rules for leap years across the whole time-line.814* In general, a year is a leap year if it is divisible by four without815* remainder. However, years divisible by 100, are not leap years, with816* the exception of years divisible by 400 which are.817* <p>818* For example, 1904 is a leap year it is divisible by 4.819* 1900 was not a leap year as it is divisible by 100, however 2000 was a820* leap year as it is divisible by 400.821* <p>822* The calculation is proleptic - applying the same rules into the far future and far past.823* This is historically inaccurate, but is correct for the ISO-8601 standard.824*825* @return true if the year is leap, false otherwise826*/827@Override // override for Javadoc and performance828public boolean isLeapYear() {829return IsoChronology.INSTANCE.isLeapYear(year);830}831832/**833* Returns the length of the month represented by this date.834* <p>835* This returns the length of the month in days.836* For example, a date in January would return 31.837*838* @return the length of the month in days839*/840@Override841public int lengthOfMonth() {842switch (month) {843case 2:844return (isLeapYear() ? 29 : 28);845case 4:846case 6:847case 9:848case 11:849return 30;850default:851return 31;852}853}854855/**856* Returns the length of the year represented by this date.857* <p>858* This returns the length of the year in days, either 365 or 366.859*860* @return 366 if the year is leap, 365 otherwise861*/862@Override // override for Javadoc and performance863public int lengthOfYear() {864return (isLeapYear() ? 366 : 365);865}866867//-----------------------------------------------------------------------868/**869* Returns an adjusted copy of this date.870* <p>871* This returns a {@code LocalDate}, based on this one, with the date adjusted.872* The adjustment takes place using the specified adjuster strategy object.873* Read the documentation of the adjuster to understand what adjustment will be made.874* <p>875* A simple adjuster might simply set the one of the fields, such as the year field.876* A more complex adjuster might set the date to the last day of the month.877* <p>878* A selection of common adjustments is provided in879* {@link java.time.temporal.TemporalAdjusters TemporalAdjusters}.880* These include finding the "last day of the month" and "next Wednesday".881* Key date-time classes also implement the {@code TemporalAdjuster} interface,882* such as {@link Month} and {@link java.time.MonthDay MonthDay}.883* The adjuster is responsible for handling special cases, such as the varying884* lengths of month and leap years.885* <p>886* For example this code returns a date on the last day of July:887* <pre>888* import static java.time.Month.*;889* import static java.time.temporal.TemporalAdjusters.*;890*891* result = localDate.with(JULY).with(lastDayOfMonth());892* </pre>893* <p>894* The result of this method is obtained by invoking the895* {@link TemporalAdjuster#adjustInto(Temporal)} method on the896* specified adjuster passing {@code this} as the argument.897* <p>898* This instance is immutable and unaffected by this method call.899*900* @param adjuster the adjuster to use, not null901* @return a {@code LocalDate} based on {@code this} with the adjustment made, not null902* @throws DateTimeException if the adjustment cannot be made903* @throws ArithmeticException if numeric overflow occurs904*/905@Override906public LocalDate with(TemporalAdjuster adjuster) {907// optimizations908if (adjuster instanceof LocalDate) {909return (LocalDate) adjuster;910}911return (LocalDate) adjuster.adjustInto(this);912}913914/**915* Returns a copy of this date with the specified field set to a new value.916* <p>917* This returns a {@code LocalDate}, based on this one, with the value918* for the specified field changed.919* This can be used to change any supported field, such as the year, month or day-of-month.920* If it is not possible to set the value, because the field is not supported or for921* some other reason, an exception is thrown.922* <p>923* In some cases, changing the specified field can cause the resulting date to become invalid,924* such as changing the month from 31st January to February would make the day-of-month invalid.925* In cases like this, the field is responsible for resolving the date. Typically it will choose926* the previous valid date, which would be the last valid day of February in this example.927* <p>928* If the field is a {@link ChronoField} then the adjustment is implemented here.929* The supported fields behave as follows:930* <ul>931* <li>{@code DAY_OF_WEEK} -932* Returns a {@code LocalDate} with the specified day-of-week.933* The date is adjusted up to 6 days forward or backward within the boundary934* of a Monday to Sunday week.935* <li>{@code ALIGNED_DAY_OF_WEEK_IN_MONTH} -936* Returns a {@code LocalDate} with the specified aligned-day-of-week.937* The date is adjusted to the specified month-based aligned-day-of-week.938* Aligned weeks are counted such that the first week of a given month starts939* on the first day of that month.940* This may cause the date to be moved up to 6 days into the following month.941* <li>{@code ALIGNED_DAY_OF_WEEK_IN_YEAR} -942* Returns a {@code LocalDate} with the specified aligned-day-of-week.943* The date is adjusted to the specified year-based aligned-day-of-week.944* Aligned weeks are counted such that the first week of a given year starts945* on the first day of that year.946* This may cause the date to be moved up to 6 days into the following year.947* <li>{@code DAY_OF_MONTH} -948* Returns a {@code LocalDate} with the specified day-of-month.949* The month and year will be unchanged. If the day-of-month is invalid for the950* year and month, then a {@code DateTimeException} is thrown.951* <li>{@code DAY_OF_YEAR} -952* Returns a {@code LocalDate} with the specified day-of-year.953* The year will be unchanged. If the day-of-year is invalid for the954* year, then a {@code DateTimeException} is thrown.955* <li>{@code EPOCH_DAY} -956* Returns a {@code LocalDate} with the specified epoch-day.957* This completely replaces the date and is equivalent to {@link #ofEpochDay(long)}.958* <li>{@code ALIGNED_WEEK_OF_MONTH} -959* Returns a {@code LocalDate} with the specified aligned-week-of-month.960* Aligned weeks are counted such that the first week of a given month starts961* on the first day of that month.962* This adjustment moves the date in whole week chunks to match the specified week.963* The result will have the same day-of-week as this date.964* This may cause the date to be moved into the following month.965* <li>{@code ALIGNED_WEEK_OF_YEAR} -966* Returns a {@code LocalDate} with the specified aligned-week-of-year.967* Aligned weeks are counted such that the first week of a given year starts968* on the first day of that year.969* This adjustment moves the date in whole week chunks to match the specified week.970* The result will have the same day-of-week as this date.971* This may cause the date to be moved into the following year.972* <li>{@code MONTH_OF_YEAR} -973* Returns a {@code LocalDate} with the specified month-of-year.974* The year will be unchanged. The day-of-month will also be unchanged,975* unless it would be invalid for the new month and year. In that case, the976* day-of-month is adjusted to the maximum valid value for the new month and year.977* <li>{@code PROLEPTIC_MONTH} -978* Returns a {@code LocalDate} with the specified proleptic-month.979* The day-of-month will be unchanged, unless it would be invalid for the new month980* and year. In that case, the day-of-month is adjusted to the maximum valid value981* for the new month and year.982* <li>{@code YEAR_OF_ERA} -983* Returns a {@code LocalDate} with the specified year-of-era.984* The era and month will be unchanged. The day-of-month will also be unchanged,985* unless it would be invalid for the new month and year. In that case, the986* day-of-month is adjusted to the maximum valid value for the new month and year.987* <li>{@code YEAR} -988* Returns a {@code LocalDate} with the specified year.989* The month will be unchanged. The day-of-month will also be unchanged,990* unless it would be invalid for the new month and year. In that case, the991* day-of-month is adjusted to the maximum valid value for the new month and year.992* <li>{@code ERA} -993* Returns a {@code LocalDate} with the specified era.994* The year-of-era and month will be unchanged. The day-of-month will also be unchanged,995* unless it would be invalid for the new month and year. In that case, the996* day-of-month is adjusted to the maximum valid value for the new month and year.997* </ul>998* <p>999* In all cases, if the new value is outside the valid range of values for the field1000* then a {@code DateTimeException} will be thrown.1001* <p>1002* All other {@code ChronoField} instances will throw an {@code UnsupportedTemporalTypeException}.1003* <p>1004* If the field is not a {@code ChronoField}, then the result of this method1005* is obtained by invoking {@code TemporalField.adjustInto(Temporal, long)}1006* passing {@code this} as the argument. In this case, the field determines1007* whether and how to adjust the instant.1008* <p>1009* This instance is immutable and unaffected by this method call.1010*1011* @param field the field to set in the result, not null1012* @param newValue the new value of the field in the result1013* @return a {@code LocalDate} based on {@code this} with the specified field set, not null1014* @throws DateTimeException if the field cannot be set1015* @throws UnsupportedTemporalTypeException if the field is not supported1016* @throws ArithmeticException if numeric overflow occurs1017*/1018@Override1019public LocalDate with(TemporalField field, long newValue) {1020if (field instanceof ChronoField) {1021ChronoField f = (ChronoField) field;1022f.checkValidValue(newValue);1023switch (f) {1024case DAY_OF_WEEK: return plusDays(newValue - getDayOfWeek().getValue());1025case ALIGNED_DAY_OF_WEEK_IN_MONTH: return plusDays(newValue - getLong(ALIGNED_DAY_OF_WEEK_IN_MONTH));1026case ALIGNED_DAY_OF_WEEK_IN_YEAR: return plusDays(newValue - getLong(ALIGNED_DAY_OF_WEEK_IN_YEAR));1027case DAY_OF_MONTH: return withDayOfMonth((int) newValue);1028case DAY_OF_YEAR: return withDayOfYear((int) newValue);1029case EPOCH_DAY: return LocalDate.ofEpochDay(newValue);1030case ALIGNED_WEEK_OF_MONTH: return plusWeeks(newValue - getLong(ALIGNED_WEEK_OF_MONTH));1031case ALIGNED_WEEK_OF_YEAR: return plusWeeks(newValue - getLong(ALIGNED_WEEK_OF_YEAR));1032case MONTH_OF_YEAR: return withMonth((int) newValue);1033case PROLEPTIC_MONTH: return plusMonths(newValue - getProlepticMonth());1034case YEAR_OF_ERA: return withYear((int) (year >= 1 ? newValue : 1 - newValue));1035case YEAR: return withYear((int) newValue);1036case ERA: return (getLong(ERA) == newValue ? this : withYear(1 - year));1037}1038throw new UnsupportedTemporalTypeException("Unsupported field: " + field);1039}1040return field.adjustInto(this, newValue);1041}10421043//-----------------------------------------------------------------------1044/**1045* Returns a copy of this {@code LocalDate} with the year altered.1046* <p>1047* If the day-of-month is invalid for the year, it will be changed to the last valid day of the month.1048* <p>1049* This instance is immutable and unaffected by this method call.1050*1051* @param year the year to set in the result, from MIN_YEAR to MAX_YEAR1052* @return a {@code LocalDate} based on this date with the requested year, not null1053* @throws DateTimeException if the year value is invalid1054*/1055public LocalDate withYear(int year) {1056if (this.year == year) {1057return this;1058}1059YEAR.checkValidValue(year);1060return resolvePreviousValid(year, month, day);1061}10621063/**1064* Returns a copy of this {@code LocalDate} with the month-of-year altered.1065* <p>1066* If the day-of-month is invalid for the year, it will be changed to the last valid day of the month.1067* <p>1068* This instance is immutable and unaffected by this method call.1069*1070* @param month the month-of-year to set in the result, from 1 (January) to 12 (December)1071* @return a {@code LocalDate} based on this date with the requested month, not null1072* @throws DateTimeException if the month-of-year value is invalid1073*/1074public LocalDate withMonth(int month) {1075if (this.month == month) {1076return this;1077}1078MONTH_OF_YEAR.checkValidValue(month);1079return resolvePreviousValid(year, month, day);1080}10811082/**1083* Returns a copy of this {@code LocalDate} with the day-of-month altered.1084* <p>1085* If the resulting date is invalid, an exception is thrown.1086* <p>1087* This instance is immutable and unaffected by this method call.1088*1089* @param dayOfMonth the day-of-month to set in the result, from 1 to 28-311090* @return a {@code LocalDate} based on this date with the requested day, not null1091* @throws DateTimeException if the day-of-month value is invalid,1092* or if the day-of-month is invalid for the month-year1093*/1094public LocalDate withDayOfMonth(int dayOfMonth) {1095if (this.day == dayOfMonth) {1096return this;1097}1098return of(year, month, dayOfMonth);1099}11001101/**1102* Returns a copy of this {@code LocalDate} with the day-of-year altered.1103* <p>1104* If the resulting date is invalid, an exception is thrown.1105* <p>1106* This instance is immutable and unaffected by this method call.1107*1108* @param dayOfYear the day-of-year to set in the result, from 1 to 365-3661109* @return a {@code LocalDate} based on this date with the requested day, not null1110* @throws DateTimeException if the day-of-year value is invalid,1111* or if the day-of-year is invalid for the year1112*/1113public LocalDate withDayOfYear(int dayOfYear) {1114if (this.getDayOfYear() == dayOfYear) {1115return this;1116}1117return ofYearDay(year, dayOfYear);1118}11191120//-----------------------------------------------------------------------1121/**1122* Returns a copy of this date with the specified amount added.1123* <p>1124* This returns a {@code LocalDate}, based on this one, with the specified amount added.1125* The amount is typically {@link Period} but may be any other type implementing1126* the {@link TemporalAmount} interface.1127* <p>1128* The calculation is delegated to the amount object by calling1129* {@link TemporalAmount#addTo(Temporal)}. The amount implementation is free1130* to implement the addition in any way it wishes, however it typically1131* calls back to {@link #plus(long, TemporalUnit)}. Consult the documentation1132* of the amount implementation to determine if it can be successfully added.1133* <p>1134* This instance is immutable and unaffected by this method call.1135*1136* @param amountToAdd the amount to add, not null1137* @return a {@code LocalDate} based on this date with the addition made, not null1138* @throws DateTimeException if the addition cannot be made1139* @throws ArithmeticException if numeric overflow occurs1140*/1141@Override1142public LocalDate plus(TemporalAmount amountToAdd) {1143if (amountToAdd instanceof Period) {1144Period periodToAdd = (Period) amountToAdd;1145return plusMonths(periodToAdd.toTotalMonths()).plusDays(periodToAdd.getDays());1146}1147Objects.requireNonNull(amountToAdd, "amountToAdd");1148return (LocalDate) amountToAdd.addTo(this);1149}11501151/**1152* Returns a copy of this date with the specified amount added.1153* <p>1154* This returns a {@code LocalDate}, based on this one, with the amount1155* in terms of the unit added. If it is not possible to add the amount, because the1156* unit is not supported or for some other reason, an exception is thrown.1157* <p>1158* In some cases, adding the amount can cause the resulting date to become invalid.1159* For example, adding one month to 31st January would result in 31st February.1160* In cases like this, the unit is responsible for resolving the date.1161* Typically it will choose the previous valid date, which would be the last valid1162* day of February in this example.1163* <p>1164* If the field is a {@link ChronoUnit} then the addition is implemented here.1165* The supported fields behave as follows:1166* <ul>1167* <li>{@code DAYS} -1168* Returns a {@code LocalDate} with the specified number of days added.1169* This is equivalent to {@link #plusDays(long)}.1170* <li>{@code WEEKS} -1171* Returns a {@code LocalDate} with the specified number of weeks added.1172* This is equivalent to {@link #plusWeeks(long)} and uses a 7 day week.1173* <li>{@code MONTHS} -1174* Returns a {@code LocalDate} with the specified number of months added.1175* This is equivalent to {@link #plusMonths(long)}.1176* The day-of-month will be unchanged unless it would be invalid for the new1177* month and year. In that case, the day-of-month is adjusted to the maximum1178* valid value for the new month and year.1179* <li>{@code YEARS} -1180* Returns a {@code LocalDate} with the specified number of years added.1181* This is equivalent to {@link #plusYears(long)}.1182* The day-of-month will be unchanged unless it would be invalid for the new1183* month and year. In that case, the day-of-month is adjusted to the maximum1184* valid value for the new month and year.1185* <li>{@code DECADES} -1186* Returns a {@code LocalDate} with the specified number of decades added.1187* This is equivalent to calling {@link #plusYears(long)} with the amount1188* multiplied by 10.1189* The day-of-month will be unchanged unless it would be invalid for the new1190* month and year. In that case, the day-of-month is adjusted to the maximum1191* valid value for the new month and year.1192* <li>{@code CENTURIES} -1193* Returns a {@code LocalDate} with the specified number of centuries added.1194* This is equivalent to calling {@link #plusYears(long)} with the amount1195* multiplied by 100.1196* The day-of-month will be unchanged unless it would be invalid for the new1197* month and year. In that case, the day-of-month is adjusted to the maximum1198* valid value for the new month and year.1199* <li>{@code MILLENNIA} -1200* Returns a {@code LocalDate} with the specified number of millennia added.1201* This is equivalent to calling {@link #plusYears(long)} with the amount1202* multiplied by 1,000.1203* The day-of-month will be unchanged unless it would be invalid for the new1204* month and year. In that case, the day-of-month is adjusted to the maximum1205* valid value for the new month and year.1206* <li>{@code ERAS} -1207* Returns a {@code LocalDate} with the specified number of eras added.1208* Only two eras are supported so the amount must be one, zero or minus one.1209* If the amount is non-zero then the year is changed such that the year-of-era1210* is unchanged.1211* The day-of-month will be unchanged unless it would be invalid for the new1212* month and year. In that case, the day-of-month is adjusted to the maximum1213* valid value for the new month and year.1214* </ul>1215* <p>1216* All other {@code ChronoUnit} instances will throw an {@code UnsupportedTemporalTypeException}.1217* <p>1218* If the field is not a {@code ChronoUnit}, then the result of this method1219* is obtained by invoking {@code TemporalUnit.addTo(Temporal, long)}1220* passing {@code this} as the argument. In this case, the unit determines1221* whether and how to perform the addition.1222* <p>1223* This instance is immutable and unaffected by this method call.1224*1225* @param amountToAdd the amount of the unit to add to the result, may be negative1226* @param unit the unit of the amount to add, not null1227* @return a {@code LocalDate} based on this date with the specified amount added, not null1228* @throws DateTimeException if the addition cannot be made1229* @throws UnsupportedTemporalTypeException if the unit is not supported1230* @throws ArithmeticException if numeric overflow occurs1231*/1232@Override1233public LocalDate plus(long amountToAdd, TemporalUnit unit) {1234if (unit instanceof ChronoUnit) {1235ChronoUnit f = (ChronoUnit) unit;1236switch (f) {1237case DAYS: return plusDays(amountToAdd);1238case WEEKS: return plusWeeks(amountToAdd);1239case MONTHS: return plusMonths(amountToAdd);1240case YEARS: return plusYears(amountToAdd);1241case DECADES: return plusYears(Math.multiplyExact(amountToAdd, 10));1242case CENTURIES: return plusYears(Math.multiplyExact(amountToAdd, 100));1243case MILLENNIA: return plusYears(Math.multiplyExact(amountToAdd, 1000));1244case ERAS: return with(ERA, Math.addExact(getLong(ERA), amountToAdd));1245}1246throw new UnsupportedTemporalTypeException("Unsupported unit: " + unit);1247}1248return unit.addTo(this, amountToAdd);1249}12501251//-----------------------------------------------------------------------1252/**1253* Returns a copy of this {@code LocalDate} with the specified number of years added.1254* <p>1255* This method adds the specified amount to the years field in three steps:1256* <ol>1257* <li>Add the input years to the year field</li>1258* <li>Check if the resulting date would be invalid</li>1259* <li>Adjust the day-of-month to the last valid day if necessary</li>1260* </ol>1261* <p>1262* For example, 2008-02-29 (leap year) plus one year would result in the1263* invalid date 2009-02-29 (standard year). Instead of returning an invalid1264* result, the last valid day of the month, 2009-02-28, is selected instead.1265* <p>1266* This instance is immutable and unaffected by this method call.1267*1268* @param yearsToAdd the years to add, may be negative1269* @return a {@code LocalDate} based on this date with the years added, not null1270* @throws DateTimeException if the result exceeds the supported date range1271*/1272public LocalDate plusYears(long yearsToAdd) {1273if (yearsToAdd == 0) {1274return this;1275}1276int newYear = YEAR.checkValidIntValue(year + yearsToAdd); // safe overflow1277return resolvePreviousValid(newYear, month, day);1278}12791280/**1281* Returns a copy of this {@code LocalDate} with the specified number of months added.1282* <p>1283* This method adds the specified amount to the months field in three steps:1284* <ol>1285* <li>Add the input months to the month-of-year field</li>1286* <li>Check if the resulting date would be invalid</li>1287* <li>Adjust the day-of-month to the last valid day if necessary</li>1288* </ol>1289* <p>1290* For example, 2007-03-31 plus one month would result in the invalid date1291* 2007-04-31. Instead of returning an invalid result, the last valid day1292* of the month, 2007-04-30, is selected instead.1293* <p>1294* This instance is immutable and unaffected by this method call.1295*1296* @param monthsToAdd the months to add, may be negative1297* @return a {@code LocalDate} based on this date with the months added, not null1298* @throws DateTimeException if the result exceeds the supported date range1299*/1300public LocalDate plusMonths(long monthsToAdd) {1301if (monthsToAdd == 0) {1302return this;1303}1304long monthCount = year * 12L + (month - 1);1305long calcMonths = monthCount + monthsToAdd; // safe overflow1306int newYear = YEAR.checkValidIntValue(Math.floorDiv(calcMonths, 12));1307int newMonth = (int)Math.floorMod(calcMonths, 12) + 1;1308return resolvePreviousValid(newYear, newMonth, day);1309}13101311/**1312* Returns a copy of this {@code LocalDate} with the specified number of weeks added.1313* <p>1314* This method adds the specified amount in weeks to the days field incrementing1315* the month and year fields as necessary to ensure the result remains valid.1316* The result is only invalid if the maximum/minimum year is exceeded.1317* <p>1318* For example, 2008-12-31 plus one week would result in 2009-01-07.1319* <p>1320* This instance is immutable and unaffected by this method call.1321*1322* @param weeksToAdd the weeks to add, may be negative1323* @return a {@code LocalDate} based on this date with the weeks added, not null1324* @throws DateTimeException if the result exceeds the supported date range1325*/1326public LocalDate plusWeeks(long weeksToAdd) {1327return plusDays(Math.multiplyExact(weeksToAdd, 7));1328}13291330/**1331* Returns a copy of this {@code LocalDate} with the specified number of days added.1332* <p>1333* This method adds the specified amount to the days field incrementing the1334* month and year fields as necessary to ensure the result remains valid.1335* The result is only invalid if the maximum/minimum year is exceeded.1336* <p>1337* For example, 2008-12-31 plus one day would result in 2009-01-01.1338* <p>1339* This instance is immutable and unaffected by this method call.1340*1341* @param daysToAdd the days to add, may be negative1342* @return a {@code LocalDate} based on this date with the days added, not null1343* @throws DateTimeException if the result exceeds the supported date range1344*/1345public LocalDate plusDays(long daysToAdd) {1346if (daysToAdd == 0) {1347return this;1348}1349long mjDay = Math.addExact(toEpochDay(), daysToAdd);1350return LocalDate.ofEpochDay(mjDay);1351}13521353//-----------------------------------------------------------------------1354/**1355* Returns a copy of this date with the specified amount subtracted.1356* <p>1357* This returns a {@code LocalDate}, based on this one, with the specified amount subtracted.1358* The amount is typically {@link Period} but may be any other type implementing1359* the {@link TemporalAmount} interface.1360* <p>1361* The calculation is delegated to the amount object by calling1362* {@link TemporalAmount#subtractFrom(Temporal)}. The amount implementation is free1363* to implement the subtraction in any way it wishes, however it typically1364* calls back to {@link #minus(long, TemporalUnit)}. Consult the documentation1365* of the amount implementation to determine if it can be successfully subtracted.1366* <p>1367* This instance is immutable and unaffected by this method call.1368*1369* @param amountToSubtract the amount to subtract, not null1370* @return a {@code LocalDate} based on this date with the subtraction made, not null1371* @throws DateTimeException if the subtraction cannot be made1372* @throws ArithmeticException if numeric overflow occurs1373*/1374@Override1375public LocalDate minus(TemporalAmount amountToSubtract) {1376if (amountToSubtract instanceof Period) {1377Period periodToSubtract = (Period) amountToSubtract;1378return minusMonths(periodToSubtract.toTotalMonths()).minusDays(periodToSubtract.getDays());1379}1380Objects.requireNonNull(amountToSubtract, "amountToSubtract");1381return (LocalDate) amountToSubtract.subtractFrom(this);1382}13831384/**1385* Returns a copy of this date with the specified amount subtracted.1386* <p>1387* This returns a {@code LocalDate}, based on this one, with the amount1388* in terms of the unit subtracted. If it is not possible to subtract the amount,1389* because the unit is not supported or for some other reason, an exception is thrown.1390* <p>1391* This method is equivalent to {@link #plus(long, TemporalUnit)} with the amount negated.1392* See that method for a full description of how addition, and thus subtraction, works.1393* <p>1394* This instance is immutable and unaffected by this method call.1395*1396* @param amountToSubtract the amount of the unit to subtract from the result, may be negative1397* @param unit the unit of the amount to subtract, not null1398* @return a {@code LocalDate} based on this date with the specified amount subtracted, not null1399* @throws DateTimeException if the subtraction cannot be made1400* @throws UnsupportedTemporalTypeException if the unit is not supported1401* @throws ArithmeticException if numeric overflow occurs1402*/1403@Override1404public LocalDate minus(long amountToSubtract, TemporalUnit unit) {1405return (amountToSubtract == Long.MIN_VALUE ? plus(Long.MAX_VALUE, unit).plus(1, unit) : plus(-amountToSubtract, unit));1406}14071408//-----------------------------------------------------------------------1409/**1410* Returns a copy of this {@code LocalDate} with the specified number of years subtracted.1411* <p>1412* This method subtracts the specified amount from the years field in three steps:1413* <ol>1414* <li>Subtract the input years from the year field</li>1415* <li>Check if the resulting date would be invalid</li>1416* <li>Adjust the day-of-month to the last valid day if necessary</li>1417* </ol>1418* <p>1419* For example, 2008-02-29 (leap year) minus one year would result in the1420* invalid date 2007-02-29 (standard year). Instead of returning an invalid1421* result, the last valid day of the month, 2007-02-28, is selected instead.1422* <p>1423* This instance is immutable and unaffected by this method call.1424*1425* @param yearsToSubtract the years to subtract, may be negative1426* @return a {@code LocalDate} based on this date with the years subtracted, not null1427* @throws DateTimeException if the result exceeds the supported date range1428*/1429public LocalDate minusYears(long yearsToSubtract) {1430return (yearsToSubtract == Long.MIN_VALUE ? plusYears(Long.MAX_VALUE).plusYears(1) : plusYears(-yearsToSubtract));1431}14321433/**1434* Returns a copy of this {@code LocalDate} with the specified number of months subtracted.1435* <p>1436* This method subtracts the specified amount from the months field in three steps:1437* <ol>1438* <li>Subtract the input months from the month-of-year field</li>1439* <li>Check if the resulting date would be invalid</li>1440* <li>Adjust the day-of-month to the last valid day if necessary</li>1441* </ol>1442* <p>1443* For example, 2007-03-31 minus one month would result in the invalid date1444* 2007-02-31. Instead of returning an invalid result, the last valid day1445* of the month, 2007-02-28, is selected instead.1446* <p>1447* This instance is immutable and unaffected by this method call.1448*1449* @param monthsToSubtract the months to subtract, may be negative1450* @return a {@code LocalDate} based on this date with the months subtracted, not null1451* @throws DateTimeException if the result exceeds the supported date range1452*/1453public LocalDate minusMonths(long monthsToSubtract) {1454return (monthsToSubtract == Long.MIN_VALUE ? plusMonths(Long.MAX_VALUE).plusMonths(1) : plusMonths(-monthsToSubtract));1455}14561457/**1458* Returns a copy of this {@code LocalDate} with the specified number of weeks subtracted.1459* <p>1460* This method subtracts the specified amount in weeks from the days field decrementing1461* the month and year fields as necessary to ensure the result remains valid.1462* The result is only invalid if the maximum/minimum year is exceeded.1463* <p>1464* For example, 2009-01-07 minus one week would result in 2008-12-31.1465* <p>1466* This instance is immutable and unaffected by this method call.1467*1468* @param weeksToSubtract the weeks to subtract, may be negative1469* @return a {@code LocalDate} based on this date with the weeks subtracted, not null1470* @throws DateTimeException if the result exceeds the supported date range1471*/1472public LocalDate minusWeeks(long weeksToSubtract) {1473return (weeksToSubtract == Long.MIN_VALUE ? plusWeeks(Long.MAX_VALUE).plusWeeks(1) : plusWeeks(-weeksToSubtract));1474}14751476/**1477* Returns a copy of this {@code LocalDate} with the specified number of days subtracted.1478* <p>1479* This method subtracts the specified amount from the days field decrementing the1480* month and year fields as necessary to ensure the result remains valid.1481* The result is only invalid if the maximum/minimum year is exceeded.1482* <p>1483* For example, 2009-01-01 minus one day would result in 2008-12-31.1484* <p>1485* This instance is immutable and unaffected by this method call.1486*1487* @param daysToSubtract the days to subtract, may be negative1488* @return a {@code LocalDate} based on this date with the days subtracted, not null1489* @throws DateTimeException if the result exceeds the supported date range1490*/1491public LocalDate minusDays(long daysToSubtract) {1492return (daysToSubtract == Long.MIN_VALUE ? plusDays(Long.MAX_VALUE).plusDays(1) : plusDays(-daysToSubtract));1493}14941495//-----------------------------------------------------------------------1496/**1497* Queries this date using the specified query.1498* <p>1499* This queries this date using the specified query strategy object.1500* The {@code TemporalQuery} object defines the logic to be used to1501* obtain the result. Read the documentation of the query to understand1502* what the result of this method will be.1503* <p>1504* The result of this method is obtained by invoking the1505* {@link TemporalQuery#queryFrom(TemporalAccessor)} method on the1506* specified query passing {@code this} as the argument.1507*1508* @param <R> the type of the result1509* @param query the query to invoke, not null1510* @return the query result, null may be returned (defined by the query)1511* @throws DateTimeException if unable to query (defined by the query)1512* @throws ArithmeticException if numeric overflow occurs (defined by the query)1513*/1514@SuppressWarnings("unchecked")1515@Override1516public <R> R query(TemporalQuery<R> query) {1517if (query == TemporalQueries.localDate()) {1518return (R) this;1519}1520return ChronoLocalDate.super.query(query);1521}15221523/**1524* Adjusts the specified temporal object to have the same date as this object.1525* <p>1526* This returns a temporal object of the same observable type as the input1527* with the date changed to be the same as this.1528* <p>1529* The adjustment is equivalent to using {@link Temporal#with(TemporalField, long)}1530* passing {@link ChronoField#EPOCH_DAY} as the field.1531* <p>1532* In most cases, it is clearer to reverse the calling pattern by using1533* {@link Temporal#with(TemporalAdjuster)}:1534* <pre>1535* // these two lines are equivalent, but the second approach is recommended1536* temporal = thisLocalDate.adjustInto(temporal);1537* temporal = temporal.with(thisLocalDate);1538* </pre>1539* <p>1540* This instance is immutable and unaffected by this method call.1541*1542* @param temporal the target object to be adjusted, not null1543* @return the adjusted object, not null1544* @throws DateTimeException if unable to make the adjustment1545* @throws ArithmeticException if numeric overflow occurs1546*/1547@Override // override for Javadoc1548public Temporal adjustInto(Temporal temporal) {1549return ChronoLocalDate.super.adjustInto(temporal);1550}15511552/**1553* Calculates the amount of time until another date in terms of the specified unit.1554* <p>1555* This calculates the amount of time between two {@code LocalDate}1556* objects in terms of a single {@code TemporalUnit}.1557* The start and end points are {@code this} and the specified date.1558* The result will be negative if the end is before the start.1559* The {@code Temporal} passed to this method is converted to a1560* {@code LocalDate} using {@link #from(TemporalAccessor)}.1561* For example, the amount in days between two dates can be calculated1562* using {@code startDate.until(endDate, DAYS)}.1563* <p>1564* The calculation returns a whole number, representing the number of1565* complete units between the two dates.1566* For example, the amount in months between 2012-06-15 and 2012-08-141567* will only be one month as it is one day short of two months.1568* <p>1569* There are two equivalent ways of using this method.1570* The first is to invoke this method.1571* The second is to use {@link TemporalUnit#between(Temporal, Temporal)}:1572* <pre>1573* // these two lines are equivalent1574* amount = start.until(end, MONTHS);1575* amount = MONTHS.between(start, end);1576* </pre>1577* The choice should be made based on which makes the code more readable.1578* <p>1579* The calculation is implemented in this method for {@link ChronoUnit}.1580* The units {@code DAYS}, {@code WEEKS}, {@code MONTHS}, {@code YEARS},1581* {@code DECADES}, {@code CENTURIES}, {@code MILLENNIA} and {@code ERAS}1582* are supported. Other {@code ChronoUnit} values will throw an exception.1583* <p>1584* If the unit is not a {@code ChronoUnit}, then the result of this method1585* is obtained by invoking {@code TemporalUnit.between(Temporal, Temporal)}1586* passing {@code this} as the first argument and the converted input temporal1587* as the second argument.1588* <p>1589* This instance is immutable and unaffected by this method call.1590*1591* @param endExclusive the end date, exclusive, which is converted to a {@code LocalDate}, not null1592* @param unit the unit to measure the amount in, not null1593* @return the amount of time between this date and the end date1594* @throws DateTimeException if the amount cannot be calculated, or the end1595* temporal cannot be converted to a {@code LocalDate}1596* @throws UnsupportedTemporalTypeException if the unit is not supported1597* @throws ArithmeticException if numeric overflow occurs1598*/1599@Override1600public long until(Temporal endExclusive, TemporalUnit unit) {1601LocalDate end = LocalDate.from(endExclusive);1602if (unit instanceof ChronoUnit) {1603switch ((ChronoUnit) unit) {1604case DAYS: return daysUntil(end);1605case WEEKS: return daysUntil(end) / 7;1606case MONTHS: return monthsUntil(end);1607case YEARS: return monthsUntil(end) / 12;1608case DECADES: return monthsUntil(end) / 120;1609case CENTURIES: return monthsUntil(end) / 1200;1610case MILLENNIA: return monthsUntil(end) / 12000;1611case ERAS: return end.getLong(ERA) - getLong(ERA);1612}1613throw new UnsupportedTemporalTypeException("Unsupported unit: " + unit);1614}1615return unit.between(this, end);1616}16171618long daysUntil(LocalDate end) {1619return end.toEpochDay() - toEpochDay(); // no overflow1620}16211622private long monthsUntil(LocalDate end) {1623long packed1 = getProlepticMonth() * 32L + getDayOfMonth(); // no overflow1624long packed2 = end.getProlepticMonth() * 32L + end.getDayOfMonth(); // no overflow1625return (packed2 - packed1) / 32;1626}16271628/**1629* Calculates the period between this date and another date as a {@code Period}.1630* <p>1631* This calculates the period between two dates in terms of years, months and days.1632* The start and end points are {@code this} and the specified date.1633* The result will be negative if the end is before the start.1634* The negative sign will be the same in each of year, month and day.1635* <p>1636* The calculation is performed using the ISO calendar system.1637* If necessary, the input date will be converted to ISO.1638* <p>1639* The start date is included, but the end date is not.1640* The period is calculated by removing complete months, then calculating1641* the remaining number of days, adjusting to ensure that both have the same sign.1642* The number of months is then normalized into years and months based on a 12 month year.1643* A month is considered to be complete if the end day-of-month is greater1644* than or equal to the start day-of-month.1645* For example, from {@code 2010-01-15} to {@code 2011-03-18} is "1 year, 2 months and 3 days".1646* <p>1647* There are two equivalent ways of using this method.1648* The first is to invoke this method.1649* The second is to use {@link Period#between(LocalDate, LocalDate)}:1650* <pre>1651* // these two lines are equivalent1652* period = start.until(end);1653* period = Period.between(start, end);1654* </pre>1655* The choice should be made based on which makes the code more readable.1656*1657* @param endDateExclusive the end date, exclusive, which may be in any chronology, not null1658* @return the period between this date and the end date, not null1659*/1660@Override1661public Period until(ChronoLocalDate endDateExclusive) {1662LocalDate end = LocalDate.from(endDateExclusive);1663long totalMonths = end.getProlepticMonth() - this.getProlepticMonth(); // safe1664int days = end.day - this.day;1665if (totalMonths > 0 && days < 0) {1666totalMonths--;1667LocalDate calcDate = this.plusMonths(totalMonths);1668days = (int) (end.toEpochDay() - calcDate.toEpochDay()); // safe1669} else if (totalMonths < 0 && days > 0) {1670totalMonths++;1671days -= end.lengthOfMonth();1672}1673long years = totalMonths / 12; // safe1674int months = (int) (totalMonths % 12); // safe1675return Period.of(Math.toIntExact(years), months, days);1676}16771678/**1679* Formats this date using the specified formatter.1680* <p>1681* This date will be passed to the formatter to produce a string.1682*1683* @param formatter the formatter to use, not null1684* @return the formatted date string, not null1685* @throws DateTimeException if an error occurs during printing1686*/1687@Override // override for Javadoc and performance1688public String format(DateTimeFormatter formatter) {1689Objects.requireNonNull(formatter, "formatter");1690return formatter.format(this);1691}16921693//-----------------------------------------------------------------------1694/**1695* Combines this date with a time to create a {@code LocalDateTime}.1696* <p>1697* This returns a {@code LocalDateTime} formed from this date at the specified time.1698* All possible combinations of date and time are valid.1699*1700* @param time the time to combine with, not null1701* @return the local date-time formed from this date and the specified time, not null1702*/1703@Override1704public LocalDateTime atTime(LocalTime time) {1705return LocalDateTime.of(this, time);1706}17071708/**1709* Combines this date with a time to create a {@code LocalDateTime}.1710* <p>1711* This returns a {@code LocalDateTime} formed from this date at the1712* specified hour and minute.1713* The seconds and nanosecond fields will be set to zero.1714* The individual time fields must be within their valid range.1715* All possible combinations of date and time are valid.1716*1717* @param hour the hour-of-day to use, from 0 to 231718* @param minute the minute-of-hour to use, from 0 to 591719* @return the local date-time formed from this date and the specified time, not null1720* @throws DateTimeException if the value of any field is out of range1721*/1722public LocalDateTime atTime(int hour, int minute) {1723return atTime(LocalTime.of(hour, minute));1724}17251726/**1727* Combines this date with a time to create a {@code LocalDateTime}.1728* <p>1729* This returns a {@code LocalDateTime} formed from this date at the1730* specified hour, minute and second.1731* The nanosecond field will be set to zero.1732* The individual time fields must be within their valid range.1733* All possible combinations of date and time are valid.1734*1735* @param hour the hour-of-day to use, from 0 to 231736* @param minute the minute-of-hour to use, from 0 to 591737* @param second the second-of-minute to represent, from 0 to 591738* @return the local date-time formed from this date and the specified time, not null1739* @throws DateTimeException if the value of any field is out of range1740*/1741public LocalDateTime atTime(int hour, int minute, int second) {1742return atTime(LocalTime.of(hour, minute, second));1743}17441745/**1746* Combines this date with a time to create a {@code LocalDateTime}.1747* <p>1748* This returns a {@code LocalDateTime} formed from this date at the1749* specified hour, minute, second and nanosecond.1750* The individual time fields must be within their valid range.1751* All possible combinations of date and time are valid.1752*1753* @param hour the hour-of-day to use, from 0 to 231754* @param minute the minute-of-hour to use, from 0 to 591755* @param second the second-of-minute to represent, from 0 to 591756* @param nanoOfSecond the nano-of-second to represent, from 0 to 999,999,9991757* @return the local date-time formed from this date and the specified time, not null1758* @throws DateTimeException if the value of any field is out of range1759*/1760public LocalDateTime atTime(int hour, int minute, int second, int nanoOfSecond) {1761return atTime(LocalTime.of(hour, minute, second, nanoOfSecond));1762}17631764/**1765* Combines this date with an offset time to create an {@code OffsetDateTime}.1766* <p>1767* This returns an {@code OffsetDateTime} formed from this date at the specified time.1768* All possible combinations of date and time are valid.1769*1770* @param time the time to combine with, not null1771* @return the offset date-time formed from this date and the specified time, not null1772*/1773public OffsetDateTime atTime(OffsetTime time) {1774return OffsetDateTime.of(LocalDateTime.of(this, time.toLocalTime()), time.getOffset());1775}17761777/**1778* Combines this date with the time of midnight to create a {@code LocalDateTime}1779* at the start of this date.1780* <p>1781* This returns a {@code LocalDateTime} formed from this date at the time of1782* midnight, 00:00, at the start of this date.1783*1784* @return the local date-time of midnight at the start of this date, not null1785*/1786public LocalDateTime atStartOfDay() {1787return LocalDateTime.of(this, LocalTime.MIDNIGHT);1788}17891790/**1791* Returns a zoned date-time from this date at the earliest valid time according1792* to the rules in the time-zone.1793* <p>1794* Time-zone rules, such as daylight savings, mean that not every local date-time1795* is valid for the specified zone, thus the local date-time may not be midnight.1796* <p>1797* In most cases, there is only one valid offset for a local date-time.1798* In the case of an overlap, there are two valid offsets, and the earlier one is used,1799* corresponding to the first occurrence of midnight on the date.1800* In the case of a gap, the zoned date-time will represent the instant just after the gap.1801* <p>1802* If the zone ID is a {@link ZoneOffset}, then the result always has a time of midnight.1803* <p>1804* To convert to a specific time in a given time-zone call {@link #atTime(LocalTime)}1805* followed by {@link LocalDateTime#atZone(ZoneId)}.1806*1807* @param zone the zone ID to use, not null1808* @return the zoned date-time formed from this date and the earliest valid time for the zone, not null1809*/1810public ZonedDateTime atStartOfDay(ZoneId zone) {1811Objects.requireNonNull(zone, "zone");1812// need to handle case where there is a gap from 11:30 to 00:301813// standard ZDT factory would result in 01:00 rather than 00:301814LocalDateTime ldt = atTime(LocalTime.MIDNIGHT);1815if (zone instanceof ZoneOffset == false) {1816ZoneRules rules = zone.getRules();1817ZoneOffsetTransition trans = rules.getTransition(ldt);1818if (trans != null && trans.isGap()) {1819ldt = trans.getDateTimeAfter();1820}1821}1822return ZonedDateTime.of(ldt, zone);1823}18241825//-----------------------------------------------------------------------1826@Override1827public long toEpochDay() {1828long y = year;1829long m = month;1830long total = 0;1831total += 365 * y;1832if (y >= 0) {1833total += (y + 3) / 4 - (y + 99) / 100 + (y + 399) / 400;1834} else {1835total -= y / -4 - y / -100 + y / -400;1836}1837total += ((367 * m - 362) / 12);1838total += day - 1;1839if (m > 2) {1840total--;1841if (isLeapYear() == false) {1842total--;1843}1844}1845return total - DAYS_0000_TO_1970;1846}18471848//-----------------------------------------------------------------------1849/**1850* Compares this date to another date.1851* <p>1852* The comparison is primarily based on the date, from earliest to latest.1853* It is "consistent with equals", as defined by {@link Comparable}.1854* <p>1855* If all the dates being compared are instances of {@code LocalDate},1856* then the comparison will be entirely based on the date.1857* If some dates being compared are in different chronologies, then the1858* chronology is also considered, see {@link java.time.chrono.ChronoLocalDate#compareTo}.1859*1860* @param other the other date to compare to, not null1861* @return the comparator value, negative if less, positive if greater1862*/1863@Override // override for Javadoc and performance1864public int compareTo(ChronoLocalDate other) {1865if (other instanceof LocalDate) {1866return compareTo0((LocalDate) other);1867}1868return ChronoLocalDate.super.compareTo(other);1869}18701871int compareTo0(LocalDate otherDate) {1872int cmp = (year - otherDate.year);1873if (cmp == 0) {1874cmp = (month - otherDate.month);1875if (cmp == 0) {1876cmp = (day - otherDate.day);1877}1878}1879return cmp;1880}18811882/**1883* Checks if this date is after the specified date.1884* <p>1885* This checks to see if this date represents a point on the1886* local time-line after the other date.1887* <pre>1888* LocalDate a = LocalDate.of(2012, 6, 30);1889* LocalDate b = LocalDate.of(2012, 7, 1);1890* a.isAfter(b) == false1891* a.isAfter(a) == false1892* b.isAfter(a) == true1893* </pre>1894* <p>1895* This method only considers the position of the two dates on the local time-line.1896* It does not take into account the chronology, or calendar system.1897* This is different from the comparison in {@link #compareTo(ChronoLocalDate)},1898* but is the same approach as {@link ChronoLocalDate#timeLineOrder()}.1899*1900* @param other the other date to compare to, not null1901* @return true if this date is after the specified date1902*/1903@Override // override for Javadoc and performance1904public boolean isAfter(ChronoLocalDate other) {1905if (other instanceof LocalDate) {1906return compareTo0((LocalDate) other) > 0;1907}1908return ChronoLocalDate.super.isAfter(other);1909}19101911/**1912* Checks if this date is before the specified date.1913* <p>1914* This checks to see if this date represents a point on the1915* local time-line before the other date.1916* <pre>1917* LocalDate a = LocalDate.of(2012, 6, 30);1918* LocalDate b = LocalDate.of(2012, 7, 1);1919* a.isBefore(b) == true1920* a.isBefore(a) == false1921* b.isBefore(a) == false1922* </pre>1923* <p>1924* This method only considers the position of the two dates on the local time-line.1925* It does not take into account the chronology, or calendar system.1926* This is different from the comparison in {@link #compareTo(ChronoLocalDate)},1927* but is the same approach as {@link ChronoLocalDate#timeLineOrder()}.1928*1929* @param other the other date to compare to, not null1930* @return true if this date is before the specified date1931*/1932@Override // override for Javadoc and performance1933public boolean isBefore(ChronoLocalDate other) {1934if (other instanceof LocalDate) {1935return compareTo0((LocalDate) other) < 0;1936}1937return ChronoLocalDate.super.isBefore(other);1938}19391940/**1941* Checks if this date is equal to the specified date.1942* <p>1943* This checks to see if this date represents the same point on the1944* local time-line as the other date.1945* <pre>1946* LocalDate a = LocalDate.of(2012, 6, 30);1947* LocalDate b = LocalDate.of(2012, 7, 1);1948* a.isEqual(b) == false1949* a.isEqual(a) == true1950* b.isEqual(a) == false1951* </pre>1952* <p>1953* This method only considers the position of the two dates on the local time-line.1954* It does not take into account the chronology, or calendar system.1955* This is different from the comparison in {@link #compareTo(ChronoLocalDate)}1956* but is the same approach as {@link ChronoLocalDate#timeLineOrder()}.1957*1958* @param other the other date to compare to, not null1959* @return true if this date is equal to the specified date1960*/1961@Override // override for Javadoc and performance1962public boolean isEqual(ChronoLocalDate other) {1963if (other instanceof LocalDate) {1964return compareTo0((LocalDate) other) == 0;1965}1966return ChronoLocalDate.super.isEqual(other);1967}19681969//-----------------------------------------------------------------------1970/**1971* Checks if this date is equal to another date.1972* <p>1973* Compares this {@code LocalDate} with another ensuring that the date is the same.1974* <p>1975* Only objects of type {@code LocalDate} are compared, other types return false.1976* To compare the dates of two {@code TemporalAccessor} instances, including dates1977* in two different chronologies, use {@link ChronoField#EPOCH_DAY} as a comparator.1978*1979* @param obj the object to check, null returns false1980* @return true if this is equal to the other date1981*/1982@Override1983public boolean equals(Object obj) {1984if (this == obj) {1985return true;1986}1987if (obj instanceof LocalDate) {1988return compareTo0((LocalDate) obj) == 0;1989}1990return false;1991}19921993/**1994* A hash code for this date.1995*1996* @return a suitable hash code1997*/1998@Override1999public int hashCode() {2000int yearValue = year;2001int monthValue = month;2002int dayValue = day;2003return (yearValue & 0xFFFFF800) ^ ((yearValue << 11) + (monthValue << 6) + (dayValue));2004}20052006//-----------------------------------------------------------------------2007/**2008* Outputs this date as a {@code String}, such as {@code 2007-12-03}.2009* <p>2010* The output will be in the ISO-8601 format {@code uuuu-MM-dd}.2011*2012* @return a string representation of this date, not null2013*/2014@Override2015public String toString() {2016int yearValue = year;2017int monthValue = month;2018int dayValue = day;2019int absYear = Math.abs(yearValue);2020StringBuilder buf = new StringBuilder(10);2021if (absYear < 1000) {2022if (yearValue < 0) {2023buf.append(yearValue - 10000).deleteCharAt(1);2024} else {2025buf.append(yearValue + 10000).deleteCharAt(0);2026}2027} else {2028if (yearValue > 9999) {2029buf.append('+');2030}2031buf.append(yearValue);2032}2033return buf.append(monthValue < 10 ? "-0" : "-")2034.append(monthValue)2035.append(dayValue < 10 ? "-0" : "-")2036.append(dayValue)2037.toString();2038}20392040//-----------------------------------------------------------------------2041/**2042* Writes the object using a2043* <a href="../../serialized-form.html#java.time.Ser">dedicated serialized form</a>.2044* @serialData2045* <pre>2046* out.writeByte(3); // identifies a LocalDate2047* out.writeInt(year);2048* out.writeByte(month);2049* out.writeByte(day);2050* </pre>2051*2052* @return the instance of {@code Ser}, not null2053*/2054private Object writeReplace() {2055return new Ser(Ser.LOCAL_DATE_TYPE, this);2056}20572058/**2059* Defend against malicious streams.2060*2061* @param s the stream to read2062* @throws InvalidObjectException always2063*/2064private void readObject(ObjectInputStream s) throws InvalidObjectException {2065throw new InvalidObjectException("Deserialization via serialization delegate");2066}20672068void writeExternal(DataOutput out) throws IOException {2069out.writeInt(year);2070out.writeByte(month);2071out.writeByte(day);2072}20732074static LocalDate readExternal(DataInput in) throws IOException {2075int year = in.readInt();2076int month = in.readByte();2077int dayOfMonth = in.readByte();2078return LocalDate.of(year, month, dayOfMonth);2079}20802081}208220832084