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