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