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