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